[英]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());
}
...
您需要使用提升的權限(作為管理員)運行WinForms應用程序(或VS,如果您從調試器運行WinForm應用程序),否則將不允許自主程序打開端口。
確保端口8080上沒有其他應用程序正在運行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.