ASP.Net Core - Ability to Restart Your Site Programmatically

Posted by Blake on 6/9/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

Your ASP.Net Core site typically starts up in Program.cs. The final line of your "void Main" is usually host.Run which runs your web application "until a token is triggered or a shutdown is triggered" (guess what we're going to do?). Here is a brief class that will show you how to wire up a cancellation token and then make a static method you can call anywhere in your site to trigger it. Take note of the "Shutdown()" method below.

C# (Program.cs)

using System.IO;
using System.Threading;
using Microsoft.AspNetCore.Hosting;

namespace TestSite
{
    public class Program
    {
        private static CancellationTokenSource cancelTokenSource = new System.Threading.CancellationTokenSource();

        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run(cancelTokenSource.Token);
        }

        public static void Shutdown()
        {
            cancelTokenSource.Cancel();
        }

    }
}

Now that we have that method in place, you can call the following line of code from anywhere in your site to reset the site. One odd behavior of this method is that the Shutdown doesn't seem happen immediately (this may or may not be a problem for you). On that note, proceed with caution.

C#

    // See you on the next request.
    Program.Shutdown();