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

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

  1. 完整示例演示#
    示例演示
    在这里插入图片描述

  2. 新建解决方案以及 WinForms 工程#
    1.1. 新建解决方案及工程#
    如下图所示:
    在这里插入图片描述

解决方案结构

建立空白解决方案及 Winforms 工程,
新建 Controllers 文件夹用于存放 WebApi 代码,
新建 Services 文件夹用于存放服务代码.
1.2. 拖拽控件#
绘制必要控件, 布局如下:
在这里插入图片描述

窗体布局

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

1.3. 引用相关开发包:#
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.SelfHost
2. 开发 HTTP 服务类#

/// <summary>
/// HTTP service.
/// </summary>
public class HttpService : IDisposable
{
    /// <summary>
    /// HTTP server's listening port.
    /// </summary>
    public int Port { get; set; }

    /// <summary>
    /// HTTP self hosting.
    /// </summary>
    private readonly HttpSelfHostServer _server;

    /// <summary>
    /// HTTP server.
    /// </summary>
    /// <param name="port">Listening port.</param>
    public HttpService(int port)
    {
        this.Port = port;

        var config = new HttpSelfHostConfiguration($"http://0.0.0.0:{this.Port}");

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

        _server = new HttpSelfHostServer(config);
    }

    #region HTTP Service

    /// <summary>
    /// start HTTP server.
    /// </summary>
    public Task StartHttpServer()
    {
        return _server.OpenAsync();
    }

    /// <summary>
    /// Close HTTP server.
    /// </summary>
    public Task CloseHttpServer()
    {
        return _server.CloseAsync();
    }

    #endregion

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
        _server?.Dispose();
    }
}

WebApi 自托管服务主要由 HttpSelfHostServer 实现, 其 OpenAsync 开启 HTTP 监听, CloseAsync 关闭 HTTP 监听.

Copy
config.MapHttpAttributeRoutes();
可以在 Controller 中使用路由特性.

  1. 调用 HTTP 服务#
    在 MainForm 窗体程序中引用 HTTP 服务:
public class MainForm:Form
{
    /// <summary>
    /// Http service.
    /// </summary>
    private HttpService _http;
}

3.1. 编写开启 HTTP 服务代码#

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

        /**
         * initialize http service.
         */
        _http = new HttpService(port);

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

3.2. 编写关闭 HTTP 服务代码#

/// <summary>
/// close the http server.
/// </summary>
private async void CloseButton_Click(object sender, EventArgs e)
{
    /**
     * close.
     */
    try
    {
        await _http.CloseHttpServer();
        _http.Dispose();
    }
    catch (Exception exception)
    {
        MessageBox.Show($"{exception.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
  1. 开发控制器#
/// <summary>
/// Home controller.
/// </summary>
[RoutePrefix("api/home")]
public class HomeController : ApiController
{
    /// <summary>
    /// Print the greetings
    /// </summary>
    /// <param name="name">visitor</param>
    /// <returns>greetings</returns>
    [Route("echo")]
    [HttpGet]
    public IHttpActionResult Echo(string name)
    {
        return Json(new {Name = name, Message = $"Hello, {name}"});
    }
}
  1. 合在一起#
    解决方案完整结构
    在这里插入图片描述

下载完整示例代码 (GitHub)
https://github.com/xixixixixiao/xiao-blog/tree/master/solutions/SelfHostingDemo
6. 注意事项#
程序需要拥有 管理员c#教程权限 才能开启 HTTP 监听, 在调试时, 若 Visual Studio 为拥有管理员权限, 则无法正常运行. 同样地, 在程序编译生成之后运行时亦需要权限.

作者: 芯芊

出处:https://www.cnblogs.com/xixixiao/p/run-self-hosting-owin-web-api-inside-winforms.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于C# WinForms应用程序中建立Web API服务器,你可以按照以下步骤进行操作: 1. 首先,确保你的C# WinForms项目已经创建并正常运行。 2. 在项目中添加一个新的类文件(.cs),该文件将包含Web API的控制器代码。 3. 在控制器类中,使用System.Web.Http命名空间并继承ApiController类。 4. 在控制器类中,创建要公开的API方法。你可以使用各种HTTP动词(如GET、POST、PUT、DELETE等)来处理不同的API请求。 5. 在控制器类中,使用[Route]属性来定义API方法的路由。这将决定API方法可以通过哪个URL进行访问。 6. 在控制器类中,使用[HttpGet]、[HttpPost]等属性来定义API方法的HTTP动词。 7. 在控制器类中,实现API方法的具体逻辑。这可能包括从数据库中检索数据、处理请求参数等。 8. 在WinForms应用程序的入口点(例如Main函数)中,使用System.Web.Http.SelfHost命名空间来启动Web API服务器。 9. 在Web API服务器的启动代码中,使用HttpSelfHostConfiguration类来配置服务器设置,例如指定要监听的端口号、启用跨域访问等。 10. 在Web API服务器的启动代码中,使用HttpSelfHostServer类来创建并启动服务器。 11. 运行你的C# WinForms应用程序,并确保Web API服务器已经成功启动。 现在,你的C# WinForms应用程序中就有一个Web API服务器了,可以通过API方法来处理HTTP请求。你可以使用工具(例如Postman)来测试和调试API方法。请记住,这只是一个基本的示例,你可以根据自己的需求进行更多的定制化和功能扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值