【问题标题】:Self hosting Web Api service into Windows Forms将 Web Api 服务自托管到 Windows 窗体中
【发布时间】:2012-12-27 14:46:06
【问题描述】:

我正在尝试使用以下代码在 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 应用程序中自行托管?

【问题讨论】:

  • 你解决问题了吗?

标签: c# asp.net winforms asp.net-web-api self-hosting


【解决方案1】:
  1. 您需要以提升的权限(以管理员身份)运行 WinForms 应用程序(或 VS,如果您从调试器运行 WinForm 应用程序),否则将不允许自主机打开端口。

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

【讨论】:

    【解决方案2】:

    问题在于 HttpSelfHostServer 对象在 Application.Run(...) 之前丢失,该对象包含保持程序运行的主事件循环。 using 语句确保为对象(在本例中为 server)调用 Dispose 方法,从而使其无法响应请求,从而导致 NullReferenceException 你正在经历。

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

    ...
    using (HttpSelfHostServer server = new HttpSelfHostServer(config))
    {
        server.OpenAsync().Wait();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new frmMainMenu());
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2016-01-21
      相关资源
      最近更新 更多