繁体   English   中英

将Web Api服务自托管到Windows窗体中

[英]Self hosting Web Api service into Windows Forms

我试图使用下面的代码在Windows窗体应用程序中自我托管Web Api服务

namespace MascoteAquarium.Desktop
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");
            config.Routes.MapHttpRoute(
                "DefaultApi", "api/{controller}/id", new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMainMenu());
        }
    }
}

当我尝试

http://localhost:8080/api/*(some-controller)* 

我在System.Web.Http.SelfHost.HttpSelfHostServer.ProcessRequestContext(ChannelContext channelContext,RequestContext requestContext)收到NullReferenceException

有人知道发生了什么事吗? 是否有可能在Win Forms应用程序内自托管?

问题是HttpSelfHostServer对象在Application.Run(...)之前丢失,它包含使程序保持运行的主事件循环。 using语句确保为对象调用Dispose方法,在本例中为服务器 ,从而使其无法回答请求,从而导致您遇到NullReferenceException

要修复异常,您的代码应如下所示:

...
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
    server.OpenAsync().Wait();
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new frmMainMenu());
}
...
  1. 您需要使用提升的权限(作为管理员)运行WinForms应用程序(或VS,如果您从调试器运行WinForm应用程序),否则将不允许自主程序打开端口。

  2. 确保端口8080上没有其他应用程序正在运行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM