如何停止自托管的Kestrel应用程序?

问题描述 投票:6回答:2

我有一个规范代码,可以在任务中自行托管一个asp.net mvc应用程序:

            Task hostingtask = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("hosting ffoqsi");
                IWebHost host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .UseApplicationInsights()
                    .Build();

                host.Run();
            }, canceltoken);

当我取消此任务时,将抛出ObjectDisposedException。我怎样才能优雅地关闭主持人?

asp.net-core asp.net-core-mvc kestrel-http-server
2个回答
10
投票

找到了取消Kestrel最明显的方法。运行有一个超载接受取消令牌。

  public static class WebHostExtensions
  {
    /// <summary>
    /// Runs a web application and block the calling thread until host shutdown.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    public static void Run(this IWebHost host);
    /// <summary>
    /// Runs a web application and block the calling thread until token is triggered or shutdown is triggered.
    /// </summary>
    /// <param name="host">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHost" /> to run.</param>
    /// <param name="token">The token to trigger shutdown.</param>
    public static void RunAsync(this IWebHost host, CancellationToken token);
  }

所以将取消令牌传递给

host.Run(ct);

解决它。


6
投票

您可以向您的Web服务器发送一个请求,该请求将调用控制器操作,该操作通过注入的IApplicationLifetime调用StopApplication()。它适合你吗?

https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.hosting.iapplicationlifetime

© www.soinside.com 2019 - 2024. All rights reserved.