DEV Community

Cover image for How to Host ASP.NET Core 3.1 Web Applications as Windows Service
Sumit Kharche
Sumit Kharche

Posted on

How to Host ASP.NET Core 3.1 Web Applications as Windows Service

In this article, we will be discussing how to deploy & host ASP.NET Core 3.1 Web API as a Windows Service. You may have one question in mind like why to host applications as windows service and why not on IIS. So in this article, we will see reasons behind hosting applications as windows service and we will be creating a Web API & host it as windows service. Let's grab a cup of coffee and start coding.

What is Windows Service?

According to the Microsoft documentation:

Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account.

In most of the scenarios where we have to make application long-running then Windows service is the best option. Windows services require an exe i.e executable of our application.

Why to deploy Applications as Windows Service

When we create an application we have to host it somewhere so that users can access it. We can either host it on IIS or as windows service. So below are the few reasons for hosting application as Windows service are:

  • Sometimes we host application on IIS but we don't utilize full features of IIS.
  • If the machine where we are hosting web application does not have IIS enabled or if it IIS enabled but not configure to host .NET Core application.

We have already discussed we require executable for hosting application as Windows service. So to do this .NET Core provides one deployment mode called Self-contained deployment (SCD). When we published our app as SCD then it will provide the executable of our app along with .NET Core runtime DLLs. If you don't know about the different hosting and deployment models in .NET Core then you can check out my below articles:

Hosting ASP.NET Core 3.1 Web API as Windows service

So now its time to actually host application as Windows service. First, we have to create basic ASP.NET Core 3.1 Web API. Those who don't know how to create then follow below steps.

Open Visual Studio 19 and also make sure .NET Core 3.1 is installed on your machine. Create a new project and select ASP.NET Core Web Application template and click on next:

create-new-project

Give a proper name for your application and click on Create button:

WindowsServiceDemo

Select ASP.NET Core 3.1 in the dropdown and select API and click on Create button:

API

That's it we have created our Web API.

final-web-api

Next step is we have to install a NuGet package.

hosting-nuget-package

Or

run below command in Nuget package manager console

Install-Package Microsoft.Extensions.Hosting.WindowsServices
Enter fullscreen mode Exit fullscreen mode

Now there is only one line of code for convert Web API as Windows service. Open your Program.cs and you will see the CreateHostBuilder method so add UseWindowsService() at the end of the method.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseWindowsService();
Enter fullscreen mode Exit fullscreen mode

And that’s all the code changes required.

Now next step is to deploy the application in SCD mode. So right-click on the application and select Publish option.

pick-up-target

Select a publish target as Folder and click on Advanced.. button.

advanced-setting

Select Deployment mode as Self-contained and Target Runtime as win-x64 and click on Save and then click on Create profile button.

published-button

Finally, click on the Publish button to publish the app.

You can also publish your app using dotnet CLI by running below command:

dotnet publish -c Release -r win-x64 --self-contained
Enter fullscreen mode Exit fullscreen mode

Go to bin\Release\netcoreapp3.1 and you will find the win-x64 folder which contains our published dlls.

To create Windows service open a command prompt in administrator mode and use the below command:

sc create <name of service you want to create> binPath= <path of executable of your app>
Enter fullscreen mode Exit fullscreen mode

So we will run the command as:

sc create WindowsServiceDemo binPath= "C:\Projects\WindowsServiceDemo\bin\Release\netcoreapp3.1\win-x64\WindowsServiceDemo.exe"
Enter fullscreen mode Exit fullscreen mode

So our service is created.

service

Right-click on service and click on start. So our Web API is running on URL http://localhost:5000. Our API has only one controller at present so to check whether we will get output hit the URL http://localhost:5000/weatherforecast in a browser and you will see the response:

api-response

We have successfully hosted our ASP.NET Core 3.1 Web API as Windows service.

Conclusion

In this article, I have explained what is Windows service, reasons for hosting application as Windows service. Also, demonstrate how to host the ASP.NET Core 3.1 Web API as Windows Service.

I really hope that you enjoyed this article, share it with friends and please do not hesitate to send me your thoughts or comments.

You can follow me on twitter @sumitkharche01.

Happy Coding!

Top comments (7)

Collapse
 
dn32 profile image
Marcelo Vieira de Souza
        HostStatic = CreateHostBuilder(args).Build();
        HostStatic.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        var root = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

        Console.WriteLine("Root: " + root);

        var builder = Host.CreateDefaultBuilder(args)
               .ConfigureLogging(logging =>
               {
                   logging
                   .ClearProviders()
                   .AddFilter("Microsoft", LogLevel.Error)
                   .AddFilter("System", LogLevel.Error);
               })
              .ConfigureWebHostDefaults(webBuilder =>
              {
                  webBuilder
                  .UseUrls(LocalHost)
                  .UseStartup<Startup>();
              });

        if (Utilitario.EhLinux())
            builder = builder.UseSystemd();
        else
            builder = builder.UseWindowsService();

        builder.ConfigureServices((hostContext, services) =>
          {
              services.AddHostedService<Worker>();
          });

        return builder;
    }
}


public class Worker : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        return Task.Run(() => { });
    }

    public override Task StopAsync(CancellationToken cancellationToken)
    {
        return base.StopAsync(cancellationToken);
    }
}
Collapse
 
crazyorange profile image
CrazyOrange

This doesn't work for me. I'll get Error 1053: The service did not respond to the start or control request in a timely fashion.

Collapse
 
amitdvs profile image
amitdvs • Edited

It works for me and can host API in window service. I can also run API in localhost.
My question is that now how I can map URL like someting.com in window service.
Please share a hosting doc or article, how I can map localhost to domain in window service.

Collapse
 
dn32 profile image
Marcelo Vieira de Souza

This doesn't work. I'll get Error 1053: The service did not respond to the start or control request in a timely fashion.

Collapse
 
bmarcco profile image
bmarcco

Hi, I use .Net Core Web Api with Net Core 5, and i was write Program.cs like code bellow
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
}).ConfigureWebHost(config =>
{
config.UseUrls(“http://*:5050”);

}).UseWindowsService();
}
but, when start my windows service API not working but when run manually helperService.exe it is work perfect. Do you know what the problem may be?

Collapse
 
websplee profile image
websplee

Thanks for this straight to the point publication. I have a console app that I struggled to port to a COM application for some PHP client app. So self-hosted windows service to the rescue.

Collapse
 
akashga32571314 profile image
Akash Gaikwad

I have same application which is working fine with HTTP after installing as a windows service.. but now I wanted to enable HTTPS for windows service so how we can do this.. please suggest