How to restart asp.net core app programmatically?

Solution 1:

Before you read my answer: This solution is going to stop the app and cause the application to re-enter the startup in the next request.

.NET Core 2 There may come a time when you wish to force your ASP.Net Core 2 site to recycle programmatically. Even in MVC/WebForms days this wasn't necessarily a recommended practice but alas, there is a way. ASP.Net Core 2 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 similar 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.

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()
        {
            ApplicationLifetime.StopApplication();
            return "Done";
        }

    }
}

Source: http://www.blakepell.com/asp-net-core-ability-to-restart-your-site-programatically-updated-for-2-0

Solution 2:

Update: Mirask's answer is more correct for .NET Core 2.

In Program.cs you will see the call to host.Run(). This method has an overload which accepts a System.Threading.CancellationToken. This is what I am doing:

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

Then, in my Controller I can call Program.Shutdown() and after a few seconds the application dies. If it is behind IIS, another request will automatically start the application.