Being able to restart an ASP.NET Core web application programmatically can be very useful, expecially if you've published it on a Linux host - which is what I almost always do, for a bunch of good reasons: if you want to know why, I strongly suggest to read my How to Publish and Deploy a ASP.NET Core Web Application on Linux Centos dedicated guide.
Conversely from what you might think, hosting ASP.NET Core on Linux is almost always a good idea and works very well: after nearly two years of constantly doing that, I would still strongly recommend it - unless you need to handle some specific Window-based tasks, such as dealing with MS Office files and/or using package libraries that do not exist on Linux (yet). However, since the environment is very different, there are a lot of "minor" differences that you will most likely experience (and need to address) at least once.
In this post we'll deal with one of them, which is strongly related to the deployment/publishing phase of your web application: the fact that on Linux, updating or overwriting the web.config file won't cause the Kestrel web server to always recycle/restart the app and reload the updated assemblies: this basically means that, whenever you deploy, you'll often need to restart the whole Kestrel service to replace the old assemblies with the new ones.
In order to fix that I took advantage of the IApplicationLifetime object, which exposes a very handy Shutdown() method that does exactly what its name suggests: since it's also injectable, we can easily use it on any controller through DI and then use it to implement an action method that would issue a remote restart through the web.
Here's a sample controller that does just that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[Authorize(Roles = "Admin")] public class AdminController : Controller { private IApplicationLifetime ApplicationLifetime { get; set; } public AdminController(IApplicationLifetime appLifetime) { ApplicationLifetime = appLifetime; } public IActionResult Shutdown() { ApplicationLifetime.StopApplication(); return Content("Done"); } } |
Needless to say, it's wise to protect such method - or the whole controller, like I did in the above example - with an appropriate [Authorize] attribute or any other measure to prevent it to be called from standard users and/or malevolent third-parties: in the above scenario, only authenticated administrators (the "Admin" membership role) would be able to use it.
Conclusion
That's it, at least for now: I sincerely hope that this small guide will be useful to those ASP.NET Core developers who are looking for a way to restart/recycle their web application programmatically and/or from a remote request.