简体   繁体   English

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

[英]Self hosting Web Api service into Windows Forms

I am trying to self host a Web Api service inside a windows forms application using the code below 我试图使用下面的代码在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());
        }
    }
}

When I try 当我尝试

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

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

Someone know what is happening? 有人知道发生了什么事吗? Is it possible to self host inside a Win Forms app? 是否有可能在Win Forms应用程序内自托管?

The problem is that the HttpSelfHostServer object gets lost just before Application.Run(...) , which contains the main event loop that keeps your program running. 问题是HttpSelfHostServer对象在Application.Run(...)之前丢失,它包含使程序保持运行的主事件循环。 The using statement makes sure that Dispose method gets called for the object, in this case server , thus making it unavailable for answering requests, resulting in the NullReferenceException you are experiencing. using语句确保为对象调用Dispose方法,在本例中为服务器 ,从而使其无法回答请求,从而导致您遇到NullReferenceException

To fix the exception, your code should look like this: 要修复异常,您的代码应如下所示:

...
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
    server.OpenAsync().Wait();
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new frmMainMenu());
}
...
  1. You need to run the WinForms application (or VS if you run the WinForm app from the debugger) with elevated privileges (as Admin), otherwise the self-host will not be allowed to open a port. 您需要使用提升的权限(作为管理员)运行WinForms应用程序(或VS,如果您从调试器运行WinForm应用程序),否则将不允许自主程序打开端口。

  2. Make sure no other application is running on port 8080 already 确保端口8080上没有其他应用程序正在运行

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

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