ASP.Net Core - Ability to Restart Your Site Programatically (Updated for 2.0)

Posted by Blake on 9/18/2017
)

Issue:

There may come a time when you wish to force your ASP.Net Core site to recycle programmatically. Even in MVC/WebForms days this wasn't necessarily a recommended practice but alas, there is a way. There are things in ASP.Net Core that only happen at the startup and should you need to reset/refresh those things for any reason this might come in handy (remember old hacks like editing the web.config?).

Solution

ASP.Net Core allows for the injection of an IApplicationLifetime object that will let you do a few handy things. First, it will let you register events for Startup, Shutting Down and Shutdown similiar to what might have been available via a Global.asax back in the day. But, it also exposes a method to allow you to shutdown the site (without a hack!). You'll need to inject this into your site, then simply call it. Below is an example of a controller with a route that will shutdown a site.

C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace MySite.Controllers
{
    public class WebServicesController : Controller
    {
        private IApplicationLifetime ApplicationLifetime { get; set; }

        public WebServicesController(IApplicationLifetime appLifetime)
        {
            ApplicationLifetime = appLifetime;
        }

        public async Task ShutdownSite()
        {
            // Later bro
            ApplicationLifetime.StopApplication();
            return "Ok";
        }

    }
}