Kestrel shutdown function in Startup.cs in ASP.NET Core

前端 未结 4 940
既然无缘
既然无缘 2020-11-29 07:07

Is there a shutdown function when using Microsoft.AspNet.Server.Kestrel? ASP.NET Core (formerly ASP.NET vNext) clearly has a Startup s

相关标签:
4条回答
  • 2020-11-29 07:35

    In ASP.NET Core you can register to the cancellation tokens provided by IApplicationLifetime

    public class Startup 
    {
        public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime) 
        {
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
        }
    
        private void OnShutdown()
        {
             // Do your cleanup here
        }
    }
    

    IApplicationLifetime is also exposing cancellation tokens for ApplicationStopped and ApplicationStarted as well as a StopApplication() method to stop the application.

    For .NET Core 3.0+

    From comments @Horkrine

    For .NET Core 3.0+ it is recommended to use IHostApplicationLifetime instead, as IApplicationLifetime will be deprecated soon. The rest will still work as written above with the new service

    0 讨论(0)
  • 2020-11-29 07:46

    I solved it with the application lifetime callback events

    Startup.cs

    public void Configure(IHostApplicationLifetime appLifetime) {
     appLifetime.ApplicationStarted.Register(() => {
      Console.WriteLine("Press Ctrl+C to shut down.");
     });
    
     appLifetime.ApplicationStopped.Register(() => {
      Console.WriteLine("Terminating application...");
      System.Diagnostics.Process.GetCurrentProcess().Kill();
     });
    }
    

    Program.cs

    Also, use UseConsoleLifetime() while building the host.

    Host.CreateDefaultBuilder(args).UseConsoleLifetime(opts => opts.SuppressStatusMessages = true);
    
    0 讨论(0)
  • 2020-11-29 07:58

    This class is now obsolete, please refer to the new interface IHostApplicationLifetime. More info here.

    0 讨论(0)
  • 2020-11-29 08:00

    In addition to the original answer, I had an error while trying to wire the IApplicationLifetime within the constructor.

    I solved this by doing:

    public class Startup 
    {
        public void Configure(IApplicationBuilder app) 
        {
            var applicationLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
        }
    
        private void OnShutdown()
        {
             // Do your cleanup here
        }
    }
    
    0 讨论(0)
提交回复
热议问题