Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a self hosted Kestrel application?

I have the canonical code to self host an asp.net mvc application, inside a task:

            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);

When I cancel this task, an ObjectDisposedException throws. How can I gracefully shut down the host?

like image 764
citykid Avatar asked Mar 31 '17 15:03

citykid


2 Answers

Found the most obvious way to cancel Kestrel. Run has an overload accepting a cancellation Token.

  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);
  }

So passing the cancellation token to

host.Run(ct);

solves it.

like image 159
citykid Avatar answered Nov 10 '22 08:11

citykid


You could send a request to your web server that would call a controller action that, via the injected IApplicationLifetime, would call a StopApplication(). Would it work for you?

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

like image 39
Daboul Avatar answered Nov 10 '22 08:11

Daboul