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

How to stop a self hosted Kestrel application?

我有规范代码可以在任务中自行托管 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。如何优雅地关闭主机?

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

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

找到最明显的取消 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);

解决了。