Introduction
An ASP.NET Core application can be hosted using various methods including IIS and HTTP.sys servers. This article is about hosting ASP.NET Core applications as a Windows Service. Windows Service feature is available only on Windows platform. This is one of the ways to host ASP.NET Core applications on Windows platform without using IIS.
Implementation of hosting an ASP.NET Core application as Windows services is not relevant to .NET Core. When an application is hosted as Windows Service, it can start/stop automatically if the service status is start/stop.
When ASP.NET Core applications host as a Windows service, the application must run on the .NET Framework, so we need to specify appropriate values for TargetFramework in csproj file. To demonstrate the example, I have run my application on .NET Framework 4.6.1.
- <PropertyGroup>
- <TargetFramework>net461</TargetFramework>
- </PropertyGroup>
The first step is to install Microsoft.AspNetCore.Hosting.WindowsServices package from nuGet. This package can be installed either by using NuGet Package Manager or by using .NET Core CLI.
Using nuget Package Manager
- PM > Install-Package Microsoft.AspNetCore.Hosting.WindowsServices
- > dotnet add package Microsoft.AspNetCore.Hosting.WindowsServices
This package contains the extension method named "RunAsService" for IWebHost. This extension method runs the specified web application as a Windows Service and port is blocked until the service is stopped. Here, we want to run our application as a service, so we need to call IWebHost.RunAsService() method instead of IWebHost.Run() in the main method of program.cs file. Also, we need to specify the path for content root directory to publish the location.
Program.cs
- using Microsoft.AspNetCore;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Hosting.WindowsServices;
- using System.Diagnostics;
- using System.IO;
- namespace TestApp
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
- var pathToContentRoot = Path.GetDirectoryName(pathToExe);
- var host = WebHost.CreateDefaultBuilder(args)
- .UseContentRoot(pathToContentRoot)
- .UseStartup<Startup>()
- .Build();
- host.RunAsService();
- }
- }
- }
The next step is to publish this application and register as a Windows Service. To register a Windows service, open a command shell with administrative privileges and use sc.exe command-line tool to create and start a service. In the following command, binPath is an executable of the application.
- >sc create TestService binPath="D:\PubTest\TestApp.exe"
- >sc start TestService

When the above command executes successfully and Windows service has started, we can browse the same path as when running without the service (i.e. default url is http://localhost:5000).

Provide a way to host application outside of a service
When running and hosting the application as a Windows service, it is very difficult to debug. So we can add a condition so that the application does not run as service.
- public static void Main(string[] args)
- {
- var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
- var pathToContentRoot = Path.GetDirectoryName(pathToExe);
- IWebHost host;
- if (Debugger.IsAttached || args.Contains("console"))
- {
- Debugger.Launch();
- host = WebHost.CreateDefaultBuilder()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseStartup<Startup>()
- .Build();
- host.Run();
- }
- else
- {
- host = WebHost.CreateDefaultBuilder(args)
- .UseContentRoot(pathToContentRoot)
- .UseStartup<Startup>()
- .Build();
- host.RunAsService();
- }
- }
Now, I am running my application using dotnet run commad and passing "console" string as an argument, so .NET framework hosts our application on a port configured in launchSettings.json.
- > dotnet run console

Handle starting and stopping events of Windows service
To handle OnStarting, OnStarted, and OnStopping events, we need to register our own WebHostService class that has these methods. Following are the steps for such events:
Create web host service class which derives from WebHostService class.
- public class MyWebHostService : WebHostService
- {
- public MyWebHostService(IWebHost host) : base(host)
- {
- }
- protected override void OnStarting(string[] args)
- {
- System.Diagnostics.Debugger.Launch();
- base.OnStarting(args);
- }
- protected override void OnStarted()
- {
- base.OnStarted();
- }
- protected override void OnStopping()
- {
- base.OnStopping();
- }
- }
- public static class WebHostServiceExtensions
- {
- public static void RunAsCustomService(this IWebHost host)
- {
- var webHostService = new MyWebHostService(host);
- ServiceBase.Run(webHostService);
- }
- }
- public static void Main(string[] args)
- {
- var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
- var pathToContentRoot = Path.GetDirectoryName(pathToExe);
- var host = WebHost.CreateDefaultBuilder(args)
- .UseContentRoot(pathToContentRoot)
- .UseStartup<Startup>()
- .Build();
- host.RunAsCustomService();
- }
If we want any service that is required in our custom service from dependency injection, such as a logger, that can be obtained from IWebHost.Services property using GetRequiredService method.
- public class MyWebHostService : WebHostService
- {
- private ILogger _logger;
- public MyWebHostService(IWebHost host) : base(host)
- {
- _logger = host.Services.GetRequiredService<ILogger<MyWebHostService>>();
- }
- ...
- ...
- }
Summary
This article explained about hosting ASP.NET Core applications as a Windows service. This is one of the recommended ways to host an ASP.NET Core app on Windows without using IIS.
You can view or download the source code from the following GitHub link.

Divyansh GuptaPosted Apr 18, 2019, 7:53 AM
Hi how can we change the port from default localhost:5000 to some other like localhost:9191? I tried changing it in the launchsetting.json file. however it does not work.
Vi SparksPosted Sep 12, 2018, 10:25 AM
I'm trying to follow the steps but I'm facing some problems: 1) The WebHost class is not available after installing Microsoft.AspNetCore.Hosting.WindowsServices package; 2) The Microsoft.AspNetCore.All NuGet package cannot be installed either (https://stackoverflow.com/questions/47416289/the-name-webhost-does-not-exists-in-current-context) because of getting "Package Microsoft.AspNetCore.All 2.1.0 is not compatible with net461" error; 3) Attempts to install the new version of the SDK and change application type from net461 to netcoreapp2.0 also failed (https://github.com/dotnet/core/issues/1675). What am I doing wrong?
Chris GustafsonPosted Aug 10, 2018, 8:06 AM
Thanks for the article, it's a nice accompaniment to the MS article. I wonder if you could pinpoint an issue. I have written an application that runs fine in debug, runs fine as a --console app (including running with dotnet on a different machine after publish). It also can be installed as a service. However, the service will not start. It's only failure information ends up as an Unhandled Exception in Kernelbase. I do have a fear that a couple .net 4.6.1 class libraries (business logic and domain objects) that I'm referencing and attempting to reuse are the culprit when running in service mode. What else could it be?
Parth AkbariPosted Jun 26, 2018, 2:42 AM
Able to start the service but "OnStarted()" method is not calling. OnStarting() method executed the log the related detail. service not keeping in Started state. there is no exception occur/ event viewer. When i run sc.exe query <serviceName> then able to see WIN32_EXIT_CODE : 1064 (0x428) code.
Parth AkbariPosted Jun 22, 2018, 9:01 AM
In one machine works perfect but in another machine not working. showing below error in Event log ---> Faulting application name: WebApplication5.dll, version: 1.0.0.0, time stamp: 0xa63b9a2eFaulting module name: KERNELBASE.dll, version: 6.1.7601.23889, time stamp: 0x598d50baException code: 0xe0434352 Fault offset: 0x000000000001a06d Faulting process id: 0x2358 Faulting application start time: 0x01d40a2b43da8b07 Faulting application path: D:\1\WebApplication5.dll Faulting module path: C:\Windows\system32\KERNELBASE.dll Report Id: 8a99f8f3-761e-11e8-a90d-4c72b9b183d6
Braytiner HegendornPosted Jun 19, 2018, 9:12 AM
Great article! But I have a doubt, Was necessary changed Asp.Net Core 2.1 packages to other packages. Could you explain why this?
DeepakPosted Jun 18, 2018, 4:36 AM
Great article. It has one issue logged here - http://localhost:5000 , page is not loading. link: https://github.com/jignesht24/Aspnetcore/issues/1
Tridip BhattacharjeePosted Jun 18, 2018, 3:44 AM
If possible come with a article which guide us how to work with DOM using blazor....how many ways out there to manipulate DOM with blazor. thanks
Tridip BhattacharjeePosted May 31, 2018, 6:09 AM
How to show hide html element in blazor without using javascript.....is it possible? i just read this article http://www.talkingdotnet.com/create-a-crud-app-using-blazor-and-asp-net-core/ i notice author use javascript to manipulate client side controls. so curious to know without js is it possible?
Tridip BhattacharjeePosted May 30, 2018, 3:56 AM
What would be the objective of hosting site in windows service. as far as i know windows service has no UI and it run in interactive mode. tell me what would be the advantage to host site in windows service instead of IIS? waiting for your reply. thanks
Tridip BhattacharjeePosted May 30, 2018, 3:31 AM
What would be the objective of hosting site in windows service. as far as i know windows service has no UI and it run in interactive mode. tell me what would be the advantage to host site in windows service instead of IIS? waiting for your reply. thanks
DeepakPosted May 30, 2018, 3:27 AM
I have installed the service, but website is not loading :(
Datta SalunkhePosted May 9, 2018, 2:40 AM
OnStarting and OnStopping events are not fired while start/stop a service. Please suggest me if i am missing something.
Max MundembaPosted Apr 10, 2018, 10:09 PM
Getting an error when trying to start with sc start TestService command
Tridip BhattacharjeePosted Mar 20, 2018, 7:25 AM
When we host asp.net in win service then form auth will work or not?
Dharmraj ThakurPosted Mar 17, 2018, 12:33 AM
Very helpful sir... thanks for the writeup
Tridip BhattacharjeePosted Mar 16, 2018, 4:31 AM
Nice article but still like to know why should some one host asp.net apps in winservice instead of IIS...what will be the advantage ? please mention some scenario where hosting web app in windows service make sense. thanks a lot for your great work.