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

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

sumitkharche profile image Sumit Kharche ・4 min read

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

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

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

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>

So we will run the command as:

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

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!

Posted on by:

sumitkharche profile

Sumit Kharche

@sumitkharche

Full stack developer from Pune, India. C# Corner MVP

Discussion

markdown guide
 

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.

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

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.

 

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