Hosting a .NET Core 2 Kestrel Server in a Windows Service

Full source code available here.

If you have been using the Kestrel web server with Framework 4.x, you might already be hosting Kestrel inside a Windows service. But what if you want to use Kestrel with .Net Core 2? It’s not straightforward to host that with a Windows service, but not too difficult either.

Before installing the service verify that Kestrel is running on the port you expect.

Navigate to

bin\debug\netcoreapp2.0

and type

dotnet WebApiCoreWithKestrel.dll (or whatever the name of your assembly is).

This command should start a console and at the top will be the port Kestrel is running on. If you haven’t specified anything, it will start on port 5000. I’ll show you how to change that in a later post.

Here are the steps for deploying this application as a service.

Step 1

First you need to download nssm, the Non-Sucking Service Manager and place it somewhere in your path or drop the nssm.exe into the bin\debug\netcoreapp2.0 directory of your project (you should use the release dll when deploying for real).

Step 2

Then you build you application.

Step 3

Create a good old batch file to run your dll and add one line -

dotnet WebApiCoreWithKestrel.dll

Swap in whatever the name of your application is.

Step 4

From a command prompt type - nssm install MyKestrelService

In the nssm window, click on the button to the right of path and pick the startup.bat file you created in step 3.

Click through to the Shutdown tab.

Note the Generate Control-C on shutdown. In Program.cs I’ve added a method that logs when the shutdown signal is received, you of course can perform any task you wish.

1private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
2{
3    Log.Information("Shutting down");
4}

Click Install Service

Step 5

In service manager you should now see a service called MyKestrelService, right click it and start the service.

That’s it your Kestrel server is up and running, you can hit by going to http://localhost:5000/api/values.

Full source code available here.

comments powered by Disqus

Related