Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Данное руководство устарело. Актуальное руководство: Руководство по 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.
Также можно поизвести публикацию с помощью графических средств в 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"
Запуск службы
После установки службы запустим ее с помощью команды:
Команде start
передается имя ранее установленной службы — в моем случае это MyAspService.
После установки мы можем обратиться обратиться к нашему веб-приложению из браузера по адресу http://localhost:5000:
In this article, we are going to learn how to create a .NET Core Worker Service and run it as a Windows Service.
To download the source code for this article, you can visit our GitHub repository.
So let’s get started.
Windows Services in .NET Core
We may want to create long-running background services in .NET in specific scenarios. For instance, we might want to perform some processor-intensive tasks, queue some operations in the background or schedule some operations to execute at a later time. For all these purposes, we can make use of the BackgroundService
class in .NET, which implements the IHostedService
interface.
For implementing long-running services, we can create a class inheriting from the BackgroundService
abstract class. Along with that, we’ll have to provide an implementation for the ExecuteAsync()
method, which runs when the service starts. While implementing the ExecuteAsync()
method, it should return a Task
that represents the lifetime of the long-running operation. There is also an option to create our custom background service class by implementing the IHostedService
interface if we wish to have more control over the background service functionality.
The background services that we create in .NET are cross-platform and support the inbuilt .NET features like logging, configuration, dependency injection, etc.
Don’t like the ads? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Creating the Project
For creating background services, we can use the Worker Service Template that is available with both the .NET CLI and Visual Studio. Worker Services allows for running background services through the use of a hosted service.
While creating a new project in Visual Studio, we can choose the Worker Service template.
On the other hand, If we are using the dotnet CLI, we can use the dotnet new
command and specify the project type as worker
:
dotnet new worker --name <project name>
Both these approaches will create a new project using the worker service template. Let’s examine the project in detail.
The Worker Service Template in .NET
A project we create using the worker service template will consist of 2 files – the Program
class and the Worker
class.
The Program
class will contain the code to add the Worker
class as a hosted service and run it:
IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build(); await host.RunAsync();
As we mentioned while explaining the windows services, any service that we implement should either inherit from the BackgroundService
class or a custom implementation of it. Here, the Worker
class contains the code for the service and it inherits from the BackgroundService
class, which in turn implements the IHostedService
interface:
public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } }
An instance of ILogger
is injected into the Worker
class for the logging support. Additionally, there is the ExecuteAsync()
method, which runs when the service starts. The default implementation of this method in the project template runs in a loop every second, logging the current date and time.
The Worker Service Template will provide the code for a simple background service and we can modify it to suit our requirements.
Configuring the Project
To have the support to host our application as a windows service, first, we need to install the Microsoft.Extensions.Hosting.WindowsServices
NuGet package:
dotnet add package Microsoft.Extensions.Hosting.WindowsServices
After that, we need to modify the Program
class by adding the UseWindowsService()
class:
IHost host = Host.CreateDefaultBuilder(args) .UseWindowsService(options => { options.ServiceName = "Code-Maze Service"; }) .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build();
The UseWindowsService()
extension method configures the application to work as a windows service. Along with that, we have set the service name using the options.ServiceName
property.
Similarly, let’s modify the ExecuteAsync()
method of the Worker
class to customize the log message:
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Code-Maze Service running at: {time}", DateTimeOffset.Now); await Task.Delay(60000, stoppingToken); } }
Along with that, we change the logging interval to 1 minute as well. Now the service will log the message once every minute.
By default, the windows service will write logs into the Application Event Log and we can use the Event Viewer tool for viewing those. Also, by default, a windows service will write only logs of severity Warning and above into the Event Log. That said, we can configure this behavior in the appsettings
file:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.Hosting.Lifetime": "Information" }, "EventLog": { "LogLevel": { "Default": "Information" } } } }
By adding a new section for the Event Log, we can change the default Log Level to Information, which will log the information as well.
With that, our windows service project is ready.
Publishing the Project
The next step is publishing the app.
For publishing the app, we can right-click the project in the solution explorer and then click on the Publish option. For this example, we can choose to publish our app to a local folder. This will create a Publish Profile and we can provide the following settings:
- For the Configuration setting, we can choose
Release|Any CPU
- We can choose the appropriate .NET version for the Target Framework setting
- From a portability standpoint, it is better to choose Deployment Mode as
Self-Contained
- We can choose the appropriate Target Runtime. In this example, since we are using a 64-bit Windows system, we can choose
win-x64
- By using the Target Location setting, we can specify where to publish the output
In the File Publish Options, we are going to check several checkboxes:
- Produce Single File – This will produce the output combined into a single file
- Enable ReadyToRun Compilation – This will produce the output in Ready-to-Run format
After providing these settings, we can leave any other setting with the default values. Now we can publish the project by clicking the Publish button.
This will produce a standalone executable output of the service in the specified folder location.
Creating the Windows Service
For creating a Windows Service, we can use the Windows Service Control Manager (sc.exe) tool. The service control manager operations require higher permissions as we are working directly with the operating system and hence we need to run the commands in a Windows PowerShell console with Administrator privilege.
In the PowerShell console, we can use the sc.exe create
command and provide the service name
and path
as arguments:
sc.exe create "Code-Maze Service" binpath="C:\service\CodeMazeWorkerService.exe"
Once the command executes successfully, it will create a new windows service with the name Code-Maze Service and return the output:
[SC] CreateService SUCCESS
We can verify the newly created service in the Windows Service Management Console:
By default, the service might be in the stopped state and we will have to start it manually by using the sc.exe start
command:
sc.exe start "Code-Maze Service"
Once the command executes successfully, it will provide an output similar to this one:
SERVICE_NAME: Code-Maze Service TYPE : 10 WIN32_OWN_PROCESS STATE : 2 START_PENDING (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x7d0 PID : 6720 FLAGS
This will start the windows service and it will continue to run in the background.
Verifying the Windows Service
Now we are going to verify that the windows service works as expected. For that, let’s open the Event Viewer.
Remember that we implemented the service to write a log once every minute. Within the Event Viewer, we can find the logs in the Windows Logs -> Application node. We are going to see a bunch of events related to our service there:
As soon as the service starts, the Windows Service Manager logs an event with the source as the service name. The first event with the source name Code-Maze Service
corresponds to that. We can verify this by opening that event. The event details will contain the corresponding message and details:
Apart from that, while the service is running, it logs an event every minute with the source matching the app’s namespace. All the subsequent events with the source name CodeMazeWorkerService
correspond to those. We can verify this by opening those events. Those events will contain the message that the service logs:
Great! We have verified that the windows service works as expected.
Removing the Windows Service
Once we create a windows service, it keeps on running in the background. For removing a windows service from the system, we have to first stop it and then delete it.
For stopping a windows service, we can use the sc.exe stop
command:
sc.exe stop "Code-Maze Service"
This will stop the service and provide a similar response:
SERVICE_NAME: Code-Maze Service TYPE : 10 WIN32_OWN_PROCESS STATE : 3 STOP_PENDING (STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0
Even though this will stop the service, we can still find the service in the Services Console. This is particularly useful when we just need to stop the service temporarily and may want to start it later.
On the other hand, if we no longer need the service, we can delete it using the sc.exe delete
command:
sc.exe delete "Code-Maze Service"
This will remove the service from the system and give the response:
[SC] DeleteService SUCCESS
Now if we check the Services Console, we cannot find the service as it will be completely removed from the system.
Conclusion
In this article, we discussed the Worker Service template in .NET Core and how to create a Windows Service Project using it. Additionally, we learned how to create and configure a Windows Service.
Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Windows services are programs that are automatically started when the system starts up, or when the user logs in. They run in the background and can run with a different account than the logged-in user. .NET makes it easy to create Windows services or Linux daemons as shown in this article.
Intro
Instead of creating Windows services and Linux daemons, nowadays you might think about using Docker instead. Docker orchestrators can be used to monitor and scale containers. Before creating a Windows service, you might think about this alternative. However, there are still many scenarios where Windows services are of great use.
What are some of the scenarios where Windows services are used? Looking at the services running with Windows, (start the Services app), services to update applications and the operating system (e.g. Windows Update, Microsoft Edge Update Service, Mozilla Maintenance Service, Google Update Service, AdobeUpdateService), services to store credentials for users and applications (Credential Manager), services to offer geolocation information for applications (Geolocation Service), malware checkers (Microsoft Defender Antivirus Service), services to deliver sensor data (Sensor Service), and many more. Not every of these services is implemented as a separate application – some of the services use the same executable. Looking at the properties of a service you can check the path for the executable including its command-line arguments. Many services that are part of Windows make use of the svchost.exe, the Geolocation service invokes this with the -k netsvcs -p options.
Services can be configured to automatically start when the operating system starts up (startup type Automatic). The Automatic Delayed start option allows the user to login before the service is started. Delayed started services are started after the Automatic started service. With the Manual configuration, the service starts up based on an event – e.g. a domain is joined, a firewall port is opened, a group policy is changed, or a custom event based on Event Tracing for Windows (ETW) is fired.
Create a Worker
Let’s start creating a Windows service by creating a background worker. With .NET 6, a background worker can be created using Visual Studio or the dotnet CLI command dotnet new worker.
The top-level statements created with this application use the Host
class. The method CreateDefaultBuilder
contains functionality to setup the dependency injection container, configuration, and logging. The dependency injection container managed by the Host
class is configured by invoking the method ConfigureServices
. In the generated code, the extension method AddHostedService
is used to register a background class that implements the interface IHostedService
. This interface is indirectly implemented by the Worker
class by deriving from the base class BackgroundService
. The interface IHostedService
defines the methods StartAsync
and StopAsync
. Adding a hosted service, invoking the Run
method of the host starts the host and in turn invokes the startup of the IHostedService
.
The Worker
class derives from the class BackgroundService
. BackgroundService
implements the interface IHostedService
and defines the abstract method ExecuteAsync
. This abstract method is called by the StartAsync
method in the BackgroundService
. StartAsync
is defined by the IHostedService
interface. With the implementation of the Worker
class, ExecuteAsync
uses an endless loop (until cancellation is requested) and writes a log message once a second.
The main functionality for the Host
class is creating the dependency injection container, configuration, and logging. Using CreateDefaultBuilder
, configuration is read from the configuration files appsettings.json, appsettings.{env.EnvironmentName}.json, environmental variables, and the command line.
Logging configuration is read from the section Logging within the configuration settings. Using the worker template, the configuration file appsettings.json defines logging based on the log level. The default configuration is set to Information:
If the application runs on a Windows system, the method CreateDefaultBuilder
also adds logging to the Windows event log and sets a filter provider to only log warnings and more critical issues to this provider.
Running the application, log information is written to the console. The worker writes a message every second.
info: SimpleWorkerService.Worker[0]
Worker running at: 03/17/2022 10:45:55 +01:00
info: SimpleWorkerService.Worker[0]
Worker running at: 03/17/2022 10:45:56 +01:00
info: SimpleWorkerService.Worker[0]
Worker running at: 03/17/2022 10:45:57 +01:00
info: SimpleWorkerService.Worker[0]
Worker running at: 03/17/2022 10:45:58 +01:00
info: SimpleWorkerService.Worker[0]
Worker running at: 03/17/2022 10:45:59 +01:00
Convert to a Windows Service
To build a Windows Service, you just need to add the NuGet package Microsoft.Extensions.Hosting.WindowsServices, and add the method invocation UseWindowsService
to the IHostBuilder
fluent API:
To see information level logging in the Windows event log, the filter is explicitly applied with the ConfigureLogging
method used with the host builder. The UseWindowsService
method configures the source name the same as the application name. This information is overwritten configuring the EventLogSettings
. In addition to setting the SourceName
property of the EventLogSettings
, the LogName
is set which creates a separate category for logging shown in the Event Viewer.
Because the
EventLogLoggerProvider
and theEventLogSettings
classes are only available on Windows, theOperatingSystem
class is used to check if the application is running on Windows before this API is invoked. In case your application is not used to run on Linux, you can use theSupportedOSPlatform
attribute instead. You can also specify <TargetPlatform> and specify a Windows Target Framework Moniker.
Installing and Managing the Windows Service
After building the application, the new Windows Service can be published using dotnet publish (or by using Visual Studio):
dotnet publish -c Release -o c:\sampleservice
To control Windows Services, the sc command can be used. Creating a new Windows Service is done using sc create passing the name of the service and the binPath parameter referencing the executable. This command requires administrator rights:
sc create "Sample Service" binPath= c:\sampleservice\SimpleWorkerService.exe
Using sc create, you can configure the account with which the service should run (the default is LocalSystem), services which are required to be started before this service (depend), and more.
The status of the service can be queried using the Services MMC, or with the command line sc query:
sc query "Sample Service"
After the service is created, it is stopped and need to be started:
sc start "Sample Service"
To stop and delete the service, the sc stop and sc delete commands can be used.
After starting the service, log information can be seen with the Windows Event Viewer. Because the LogName
property was set, there’s a separate category with Application and Services Logs:
Passing Arguments
With a Windows Service, it’s possible to pass command-line arguments with the service configuration. To read the arguments, the Environment
class can be used as shown in the following code snippet.
When creating the service using sc create, pay attention to leave a blank after the binPath option. You can supply the parameters within the quotes:
sc create "Sample Service" binPath= "c:\sampleservice\SimpleWorkerService.exe --p1=one --p2=two"
Web Application as Windows Service
What about hosting Kestrel as a Windows Service? There’s not a lot difference using the package Microsoft.Extensions.Hosting.WindowsServices – in principle just the API UseWindowsService needs to be invoked. Let’s get into details using the .NET 6 WebApplicationBuilder
class.
A Web API project can be created using dotnet new webapi. This template creates an API returning random weather information. With the option –use-minimal-apis, controllers are not used, and the complete functionality of the API can be defined with top-level statements. The parameter –no-https specifies to create an implementation with HTTP. Using HTTPS, it’s necessary to create and configure a certificate that’s used by the account running the service. Depending on the scenario how you use this Windows service, HTTP can be ok.
dotnet new webapi --use-minimal-apis --no-https -o ASPNETCoreWindowsService
The UseWindowsService
method is an extension method for IHostBuilder
. With .NET 6, WebApplication
and WebApplicationBuilder
are used instead of the Host
and HostBuilder
classes. Of course, you can also change the code to the old .NET 5 version. WebApplication
offers an abstraction layer of the Host
class and makes it easier to configure ASP.NET Core middleware. With .NET 5, the Startup
class has been used. Instead of using the Startup
class now everything can be done with top-level statements. The Minimal API makes use of C# 10 features and adds some APIs, e.g. a new overload of the MapGet
method. Using the WebApplicationBuilder
class, the functionality of the IHostBuilder
can be accessed using the Host
property. This property returns a ConfigureHostBuilder
instance which implements the interface IHostBuilder
. Here you can use the extension method UseWindowsService
like before. The UseWindowsService
extension method configures the content root path to AppContext.BaseDirectory
for the Windows service. Because the CreateBuilder
method already needs this directory, this directory needs to be specified with the WebApplicationOptions
as shown. To specify a log category with the Windows event logs, the EventLogSettings
are configured as before with the console application:
The Kestrel server can be configured accessing the WebHost
property of the WebApplicationBuilder
, invoking the method ConfigureKestrel
. With the sample application, the Kestrel server is configured using appsettings.json:
Now the service can be build, published, and configured as a Windows Service in the same way as mentioned before using the worker application. Opening a browser to reference the configured port with the controller route WeatherForecast returns JSON information from the API service:
http://localhost:9200/weatherforecast
Accessing the Windows Service from a different system, the Firewall needs to be configured to allow accessing this port from the outside.
Linux Daemons
What about running this application on Linux? The method UseWindowsService
checks if it’s running on Windows as a Windows service, and returns if this is not the case. With this you can run the application on the Linux system as well. To create a Linux daemon, you can add the NuGet package Microsoft.Extensions.Hosting.Systemd, and invoke the method UseSystemd
. What’s different is the configuration of systemd. To use systemd with WSL-2, you can use Distrod to run your Ubuntu environment. See a link below for Distrod.
Take away
Starting with .NET 3, the Host
class was introduced which abstracts configuration for logging, dependency injecction, and configuration in one place. Extension methods make it easy to offer more features. With this, using the NuGet package Microsoft.Extensions.Hosting.WindowsServices just one API method is required to create a Windows Service. This way, background functionalty based on the worker template, but also hosting a Kestrel server for offering ASP.NET Core Web applications and services is an easy task.
If you like this article, it would be great if you buy a coffee:
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:
Give a proper name for your application and click on Create button:
Select ASP.NET Core 3.1 in the dropdown and select API and click on Create button:
That’s it we have created our Web API.
Next step is we have to install a 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.
Select a publish target as Folder and click on Advanced..
button.
Select Deployment mode as Self-contained and Target Runtime as win-x64 and click on Save and then click on Create profile 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.
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:
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!