实现 WebApi 自托管服务宿主于 WinForms 及其交互

实现 WebApi 自托管服务宿主于 WinForms 及其交互

在 Windows 平台 Web 服务一般托管于 IIS. 在开发中, 会遇到 WinForms 或 WPF 服务端程序需要提供对外 API 作为服务. 在本文详细介绍 WebApi 自托管于 WinForms 中, WPF 或 Console 程序实现类似.

0. 完整示例演示

实现 WebApi 自托管服务宿主于 WinForms 及其交互_第1张图片

1. 新建解决方案以及 WinForms 工程

1.1 新建解决方案及工程

如下图所示:

实现 WebApi 自托管服务宿主于 WinForms 及其交互_第2张图片

1.2 拖拽控件

绘制必要控件, 布局如下:

实现 WebApi 自托管服务宿主于 WinForms 及其交互_第3张图片

备注: 绘制一个 NumericUpDown 和两个 Button 控件.

2. 开发 HTTP 服务类

/// 
/// HTTP service.
/// 
public class HttpService
{
    /// 
    /// HTTP self hosting.
    /// 
    private HttpSelfHostServer _server;

    #region HTTP Service

    /// 
    /// start HTTP server.
    /// 
    /// the port of the http server
    public void StartHttpServer(string port)
    {
        var config = new HttpSelfHostConfiguration($"http://0.0.0.0:{port}");

        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");

        this._server = new HttpSelfHostServer(config);
        this._server.OpenAsync().Wait();
    }

    /// 
    /// Close HTTP server.
    /// 
    public void CloseHttpServer()
    {
        this._server.CloseAsync().Wait();
        this._server.Dispose();
    }

    #endregion
}

WebApi 自托管服务主要由 HttpSelfHostServer 实现.

config.MapHttpAttributeRoutes();

可以在 Controller 中使用路由特性.

3. 调用 HTTP 服务

在 MainForm 窗体程序中引用 HTTP 服务:


public class MainForm:Form
{
    /// 
    /// Http service.
    /// 
    private readonly HttpService _http;

    public MainForm()
    {
        /**
         * initialize http service.
         */
        _http = new HttpService();
    }
}

3.1 编写开启 HTTP 服务代码

/// 
/// start the http server.
/// 
private void StartButton_Click(object sender, EventArgs e)
{
    /**
     * start.
     */
    try
    {
        var port = this.PortNum.Value;

        _http.StartHttpServer($"{port}");
    }
    catch (Exception exception)
    {
        MessageBox.Show($"{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

3.2 编写关闭 HTTP 服务代码

/// 
/// close the http server.
/// 
private void CloseButton_Click(object sender, EventArgs e)
{
    /**
     * close.
     */
    try
    {
        _http.CloseHttpServer();

    }
    catch (Exception exception)
    {
        MessageBox.Show($"{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

4. 开发控制器

/// 
/// Home controller.
/// 
[RoutePrefix("api/home")]
public class HomeController : ApiController
{
    /// 
    /// Print the greetings
    /// 
    /// visitor
    /// greetings
    [Route("echo")]
    [HttpGet]
    public IHttpActionResult Echo(string name)
    {
        return Json(new {Name = name, Message = $"Hello, {name}"});
    }
}

5. 合在一起

实现 WebApi 自托管服务宿主于 WinForms 及其交互_第4张图片

下载完整示例代码 (GitHub)

你可能感兴趣的:(实现 WebApi 自托管服务宿主于 WinForms 及其交互)