And*_*rey 11 c# asp.net self-hosting winforms asp.net-web-api
我试图使用下面的代码在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应用程序内自托管?
小智 10
问题是HttpSelfHostServer对象在Application.Run(...)之前丢失,它包含使程序保持运行的主事件循环.在使用语句可以确保处置方法被调用的对象,在这种情况下服务器,从而使其不能用于回答请求,导致的NullReferenceException你正在经历.
要修复异常,您的代码应如下所示:
...
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
    server.OpenAsync().Wait();
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new frmMainMenu());
}
...
您需要以提升的权限(作为管理员)运行 WinForms 应用程序(如果从调试器运行 WinForm 应用程序,则为 VS),否则将不允许自主机打开端口。
确保端口 8080 上尚未运行其他应用程序
| 归档时间: | 
 | 
| 查看次数: | 5627 次 | 
| 最近记录: |