Asp net hosting windows service

Cover image for 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.

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!

We can host ASP.NET Core apps on Windows as a Windows Service. Note that this approach does not need IIS, Apache or Nginx. So the app automatically starts whenever the system restarts.

Create ASP.NET Core MVC app

Open Visual Studio and create a new .NET app by selecting ASP.NET Core Web App (Model-View-Controller) template.

asp.net core web app mvc template

Name the app as TestWindowsService and select .NET 8.0 version and leave everything else untouched. Click the Create button to create this app.

additional information visual studio 2022

In the app, install the package Microsoft.Extensions.Hosting.WindowsServices from NuGet.

Microsoft.Extensions.Hosting.WindowsServices

Next, register windows service on the Program.cs. The code to add is given below.

builder.Services.AddWindowsService();

With this our .NET app is ready to be Hosted on a Windows Service.

Let’s publish the app by right clicking on the app in Solution Explorer and select “Publish”.

Publish .NET

Publish the app to a folder. The default location is bin\Release\net8.0\publish\ where this app gets published. I prefer to run all my services from C drive, so I created a new folder called TestWindowsService on the “C:/” drive and copied all the files inside the “publish” folder to this newly created folder. You are free to use any location of your choice.

Creating a Windows Service

In windows go to the menu and select “Run”. In the Run box enter services.msc and click OK button.

services.msc

Windows services panel will open where you can see all the the available services. You can also start, stop or pause a service from this panel.

windows services panel

We can create a new Windows Service from Windows Service Control Manager (sc.exe) tool. This service will then run our .NET app. To create a Windows Service, open Powershell as an Admistrator. Now run the below command.

sc.exe create "YogiHosting Service" binpath="C:\TestWindowsService\TestWindowsService.exe"

We have named the service as YogiHosting Service and provided the path of the app’s exe file to the binpath variable.

You will get the message – [SC] CreateService SUCCESS telling that the service is created.

sc create command

Close and re-open Window Service Panel to check this service is now created. I have shown this on the below image.

service created

By default the created service is in the stopped state, we can now run this service by the below command.

sc.exe start "YogiHosting Service"

sc start service

Well that’s it, open url – http://localhost:5000 on your browser and your app will be available. Check the below image.

ASP.NET Core app running on windows service

Other important command are the stop command which will stop the service and the delete command which deletes the service.

sc.exe stop "YogiHosting Service"
sc.exe delete "YogiHosting Service"

We can see our hosted app’s logs in Event Viewer. Check the below image.

Event Viewer

Our ASP.NET Core app is now successfully hosted from a Windows Service.

Creating a BackGround Service

We can create Background Service on our .NET apps to perform heavy tasks like scheduled jobs, eg sending emails at periodic times.

Add a class called SendEmails.cs to the app.

public class SendEmails : BackgroundService
{
    public ServiceA(ILoggerFactory loggerFactory)
    {
        Logger = loggerFactory.CreateLogger<SendEmails>();
    }

    public ILogger Logger { get; }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Logger.LogInformation("Starting");

        stoppingToken.Register(() => Logger.LogInformation("Stopping"));

        while (!stoppingToken.IsCancellationRequested)
        {
            Logger.LogInformation("Sending emails");
            
            // code to send emails
            
        }

        Logger.LogInformation("Stopped.");
    }
}

Then register this class in the Program.cs.

builder.Services.AddHostedService<SendEmails>();

Let’s me know your thoughts on this tutorial from the below comments section. Thank you.

Create ASP.NET Core App as Windows Service

In this article, we shall see how Hosting ASP.NET Core API as Windows Service can be enabled in ASP.NET Core 3.1 or 6.0 API by using UseWindowsService.

Today in this article, we will cover below aspects,

  • Getting started
  • Enable UseWindowsService for the Host
  • Hosting API as a Service
  • Summary

We shall be using an approach where we will use UseWindowsService and convert the API as a Windows service.

If you want to create ASP.NET Core API as Service (in addition to the endpoint exposed via a different HTTP route using Controller) using another approach i.e Worker template method discussed, please do visit the below article for more information.

  • Create ASP.NET Core App as Windows Service using Worker Template

Let’s now look into an approach -II

Getting started

Create ASP.NET Core API using 3.1 or 5.0 .NET Core version.

Host API as Service

Using ASP.NET Core API-App as Service -Windows service

Install Nuget Package as below,

PM> Install-Package Microsoft.Extensions.Hosting.WindowsServices

Or Using Nuget Manager,

Hosting ASP.NET Core API as Windows Service

Enable UseWindowsService for the Host

CreateDefaultBuilder generic host builder needs to be configured with UseWindowsService(). Here UseWindowsService sets the host lifetime to WindowsServiceLifetime, sets the Content Root, and enables logging to the event log with the application name as the default source name.

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

                }).ConfigureWebHost(config =>
                {
                    config.UseUrls("http://*:5050");

                }).UseWindowsService();
    }

Here I am configuring the Windows Service for the Url http://localhost:5050

As you can see we have converted our API as a service using just one line of code i.e UseWindowsService()

Let’s publish the package as self-contained and then followed by deploy using the Windows Service CLI command.

dotnet publish -c Release -r win-x64 --self-contained

or using Visual Studio

blank

Hosting API as a Service

Now we are all set to deploy the service to the services.msc.I shall install this service and validate the URLs working fine.

Please use the below command to register the service,

sc create [app-name] binPath=[filepath]

Example

sc create APIasWIN binPath="C:\Users\WebAPIasService\bin\Release\netcoreapp3.1\WebAPIasService.exe"
blank

Once hosted successfully, you shall see the service listed in the Service Console as below,

blank

Lets now execute the API routes below,

http://localhost:5050/WeatherForecast/

blank

You shall be able to execute all the routes supported by your API without any issues.

That’s All! Thank you!

Reference:

  • Hosting ASP.NET Core App as Service using Worker template -IHostedService

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

Today in this article we learned how to enable ASP.NET Core API as Service. We hosted API as a Window service using a Service console and were able to call API routes from the service easily.


Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.


Данное руководство устарело. Актуальное руководство: Руководство по ASP.NET Core 7

Последнее обновление: 12.06.2018

ASP.NET Core можно развертывать в виде обычной службы Windows без каких-либо веб-серверов, в частности, IIS.

Создадим новый проект ASP.NET Core 2.1 любого типа. Прежде всего, нам надо добавить в проект через Nuget пакет
Microsoft.AspNetCore.Hosting.WindowsServices.

После создания проекта обратимся к файлу Program.cs, который во всех проектах выглядит идентично:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace ServiceHostingApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Изменим его следующим образом:

using System.Diagnostics;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;

namespace ServiceHostingApp
{
    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();
        }
    }
}

Чтобы запустить приложение в виде службы у объекта IWebHost вызывается метод RunAsService().

Публикация

Теперь нам надо опубликовать приложение в файловой системе. Мы можем это сделать через консоль с помощью команды dotnet publish.
Для этого вначале в командной строке/терминале надо перейти к папке проекта и из нее запустить команду:

dotnet publish --configuration Release --runtime win10-x64 --output c:\myapp

Поскольку приложение будет устанавливаться в виде службы Windows и должно иметь исполняемый файл, то указывается
параметр --runtime. В данном случае служба будет устанавливаться на Windows 10 с 64-битной архитектурой. Поэтому
для этого параметра указано значение win10-x64.

Параметр --output указывает, где будет опубликовано приложение — то есть в данном случае в папке c:\myapp.

ASP.NET Core app as a Windows Service

Также можно поизвести публикацию с помощью графических средств в Visual Studio.

Создание службы

После публикации с помощью консольной утилиты sc.exe создадим службу:

sc create НАЗВАНИЕ_СЛУЖБЫ binPath= "ПУТЬ К ИСПОЛНЯЕМОМУ ФАЙЛУ EXE"

После команды create указывается имя службы. Службу можно назвать как угодно.

Параметр binPath указывает на путь к исполняемому файлу (в том числе имя самого файла).
Причем между знаком равно и путем к файлу в кавычках должен идти пробел.

Например, ранее приложение было опубликовано в папке c:\myapp. Как правило, название исполняемого файла соответствует названию проекта, то есть в моем случае
в папке c:\myapp после публикации находится исполняемый файл ServiceHostingApp.exe. И, допустим, служба буде называться
MyAspService. В этом случае команда на создание службы будет выглядеть следующим образом:

sc create MyAspService binPath= "c:\myapp\servicehostingapp.exe"

Установка приложения ASP NET Core в виде службы

Запуск службы

После установки службы запустим ее с помощью команды:

Команде start передается имя ранее установленной службы — в моем случае это MyAspService.

После установки мы можем обратиться обратиться к нашему веб-приложению из браузера по адресу http://localhost:5000:

Приложение Asp.Net Core в виде службы Windows

Sponsor: Using RabbitMQ or Azure Service Bus in your .NET systems? Well, you could just use their SDKs and roll your own serialization, routing, outbox, retries, and telemetry. I mean, seriously, how hard could it be?

In my previous blog I demonstrated how to Self Host ASP.NET Web API, which was a very basic console application leveraging Owin and Katana.

The next step in this series is how to turn your console application into a Windows service.

If you have any questions, please follow me on Twitter.

Video

If you prefer a video tutorial, here is one I published to YouTube outlining a similar example as on this post.

Windows Service Template

The typical way to create a Windows Service is by using the Windows Service template when creating a new project within Visual Studio.

The template will create a Program.cs calling ServiceBase.Run() in the Main() method.

SelfHostServiceBase is the code that will extend ServiceBase.   You would have to implement OnStart() and OnStop()

That’s simplest possible implementation.  Now when you start debugging, you are treated with this wonderful message.

service

What this means is you must build your Windows service, start it, then attach the debugger to the process.

Doesn’t sound like a fun way to debug does it?

Topself

There is a great open source project called Topshelf which allows you to create a windows service which is much easier to debug.

Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.

First thing is to install Topshelf into your project via nuget.

Install-Package Topshelf

Next we need a tiny bit of code to configure our service with topshelf.

We tell topself which class will contain our service (TopselfService) as well as which method to call when the service starts and stops.

Also, you can define which user the service should run as, as well as the name, display name and description.

Now when you debug the application, it will run just like a Console application, in which you can add breakpoints and debug.

Self Host ASP.NET Web API

To verify my web api application is responding, here is the result from my Postman call

Postman

 

Source Code

The source code for this demo is available on Github.

Next…

Next up I’ll continue adding to the demo by serving static assets from your self host application.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • По vipnet client for windows 4 x kc3
  • Некоторыми параметрами управляет ваша организация windows 2016
  • Wireshark portable windows xp
  • Установка windows на mac mini 2014
  • Windows delete files in use