We developers won’t have access to servers all the time, and without management capabilities, it will be difficut to restart a web application. However, in ASP.NET Core, there is a way for us to programmatically restart our application without requring management capabilities from server admins.

IApplicationLifetime

There is a IApplicationLifetime interface in ASP.NET Core which can handle events like start up and shut down. It provides 3 Cancellation Token, allowing us to use Action delegate to handle the ASP.NET Core website’s start and stop events:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
    appLifetime.ApplicationStarted.Register(() =>
    {
        _logger.LogInformation("Moonglade started.");
    });

    appLifetime.ApplicationStopping.Register(() =>
    {
        _logger.LogInformation("Moonglade is stopping...");
    });

    appLifetime.ApplicationStopped.Register(() =>
    {
        _logger.LogInformation("Moonglade stopped.");
    });

    // ... Other code
}

Per Microsoft document:

Cancellation TokenTriggered when…
ApplicationStartedThe host has fully started.
ApplicationStoppedThe host is completing a graceful shutdown. All requests should be processed. Shutdown blocks until this event completes.
ApplicationStoppingThe host is performing a graceful shutdown. Requests may still be processing. Shutdown blocks until this event completes.

Killing the Website

Besides these 3 events, IApplicationLifetime interface got another method named StopApplication() which can stop the current ASP.NET Core application. When the website is being stopped, ApplicationStopping and ApplicationStopped events will be fired in sequence.

We can restart our website based on this method.

Implement Restart Functionality

The most easy way for us to restart a website is to access a certain URL. Take ASP.NET Core MVC application for example:

Inject an IApplicationLifetime class into the Controller:

public class AdminController : Controller
{
    IApplicationLifetime applicationLifetime;

    public AdminController(IApplicationLifetime appLifetime)
    {
        applicationLifetime = appLifetime;
    }

    // ...
}

And use an Action to invoke the StopApplication() method:

[HttpGet("blow-me-up")]
public IActionResult BlowMeUp()
{
    applicationLifetime.StopApplication();
    return new EmptyResult();
}

Now, when I access the URL “blow-me-up“, the website will shut down itself:

To restart the application is easy. Under IIS, the next request goes to the website will start it up again. Which basically means, reopen the website in the browser again and it will start up.

Leave a comment

Your email address will not be published. Required fields are marked *