Asp net core as windows service

Данное руководство устарело. Актуальное руководство: Руководство по 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

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.

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!

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!

Become a patron at Patreon!

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:

windows service running

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:

windows services event log

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:

windows service started event

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:

windows service log event

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!

Become a patron at Patreon!

Note, this tutorial is about hosting an ASP.NET Core web app as a windows service, specifically in .NET Core 3.

If you are looking to host a web app as a service in .NET Core 2, check out this other tutorial : Hosting An ASP.NET Core Web Application As A Windows Service In .NET Core 2

If you are looking to run a Windows Service as a “worker” or for background tasks, then you’ll want this tutorial : Creating Windows Services In .NET Core – Part 3 – The “.NET Core Worker” Way


This is actually somewhat of a duplicate of a previous post I did here. But that was using .NET Core 2+, and since then, things have changed quite a bit. Well… Enough that when I tried to follow my own tutorial recently I was wondering what the hell I was going on about when nothing worked for me this time around.

Why A Web App As A Windows Service

So this tutorial is about running a Web App as a Windows Service. Why would that ever be the case? Why would you not have a web app running under something like IIS? Or why a Windows Service specifically?

Well the answer to why not under IIS is that in some cases you may not have IIS on the machine. Or you may have IIS but it’s not set up to host .NET Core apps anyway. In these cases you can do what’s called a self contained deploy (Which we’ll talk about soon), where the web app runs basically as an exe that you can double click and suddenly you have a fully fledged web server up and running – and portable too.

For the latter, why a windows service? Well if we follow the above logic and we have an exe that we can just click to run, then a windows service just gives us the ability to run on startup, run in the “background” etc. I mean, that’s basically all windows services are right? Just the OS running apps on startup and in the background.

Running Our Web App As A Service

The first thing we need to do is make our app compile down to an EXE. Well.. We don’t have to but it makes things a heck of a lot easier. To do that, we just need to edit our csproj and add the OutputType of exe. It might end up looking like so :

<PropertyGroup>
  <TargetFramework>netcoreapp3.0</TargetFramework>
  <OutputType>Exe</OutputType>
</PropertyGroup>

In previous versions of .NET Core you had to install the package Microsoft.AspNetCore.Hosting.WindowsServices , however as of right now with .NET Core 3+, you instead need to use Microsoft.Extensions.Hosting.WindowsServices . I tried searching around for when the change happened, and why, and maybe information about differences but other than opening up the source code I couldn’t find much out there. For now, take my word on it. We need to install the following package into our Web App :

Install-Package Microsoft.Extensions.Hosting.WindowsServices

Now there is just a single line we need to edit. Inside program.cs, you should have a “CreateHostBuilder” method. You might already have some custom configuration going on, but you just need to tack onto the end “UseWindowsServices()”.

return Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        }).UseWindowsService();

And that’s all the code changes required!

Deploying Our Service

… But we are obviously not done yet. We need to deploy our service right!

Open a command prompt as an Administrator, and run the following command in your project folder to publish your project :

dotnet publish -c Release

Next we can use standard Windows Service commands to install our EXE as a service. So move your command prompt to your output folder (Probably along the lines of C:\myproject\bin\Release\netcoreapp3.0\publish). And run something like so to install as a service :

sc create MyApplicationWindowsService binPath= myapplication.exe

Doing the full install is usually pretty annoying to do time and time again, so what I normally do is create an install.bat and uninstall.bat in the root of my project to run a set of commands to install/uninstall. A quick note when creating these files. Create them in something like Notepad++ to ensure that the file type is UTF8 *without BOM*. Otherwise you get all sorts of weird errors :

The contents of my install.bat file looks like :

sc create MyService binPath= %~dp0MyService.exe
sc failure MyService actions= restart/60000/restart/60000/""/60000 reset= 86400
sc start MyService
sc config MyService start=auto

Keep the weird %~dp0 character there as that tells the batch process the current directory (Weird I know!).

And the uninstall.bat :

sc stop MyService
timeout /t 5 /nobreak > NUL
sc delete MyService

Ensure these files are set to copy if newer in Visual Studio, and now when you publish your project, you only need to run the .bat files from an administrator command prompt and you are good to go!

Doing A Self Contained Deploy

We talked about it earlier that the entire reason for running the Web App as a Windows Service is so that we don’t have to install additional tools on the machine. But that only works if we are doing what’s called a “self contained” deploy. That means we deploy everything that the app requires to run right there in the publish folder rather than having to install the .NET Core runtime on the target machine.

All we need to do is run our dotnet release command with a few extra flags :

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

This tells the .NET Core SDK that we want to release as self contained, and it’s for Windows.

Your output path will change from bin\Release\netcoreapp3.0\publish  to \bin\Release\netcoreapp3.0\win-x64\publish

You’ll also note the huge amount of files in this new output directory and the size in general of the folder. But when you think about it, yeah, we are deploying the entire runtime so it should be this large.

Content Root

The fact that .NET Core is open source literally saves hours of debugging every single time I work on a greenfields project, and this time around is no different. I took a quick look at the actual source code of what the call to UseWindowsService does here. What I noticed is that it sets the content root specifically for when it’s running under a Windows Service. I wondered how this would work if I was reading a local file from disk inside my app, while running as a Windows Service. Normally I would just write something like :

File.ReadAllText("myfile.json");

But… Obviously there is something special when running under a Windows Service context. So I tried it out and my API bombed. I had to check the Event Viewer on my machine and I found :

Exception Info: System.IO.FileNotFoundException: Could not find file 'C:\WINDOWS\system32\myfile.json'.

OK. So it looks like when running as a Windows Service, the “root” of my app thinks it’s inside System32. Oof. But, again, looking at the source code from Microsoft gave me the solution. I can simply use the same way they set the content root to load my file from the correct location :

File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "myfile.json"));

And we are back up and running!

UseWindowsServiceHostASPNETCoreAPIWindowsservice | Hosting ASPNET Core API as Windows Service | TheCodeBuzz

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.

Using ASPNET Core APIApp as Service Windows service | Hosting ASPNET Core API as Windows Service | TheCodeBuzz

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,

UsingASPNETCoreAPIAppasWindowsservice | Hosting ASPNET Core API as Windows Service | TheCodeBuzz

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

UsingASPNETCoreAPIAppasWindowsserviceUseWindowsService | Hosting ASPNET Core API as Windows Service | TheCodeBuzz

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"

UsingASPNETCoreAPIasWindowsserviceUseWindowsService | Hosting ASPNET Core API as Windows Service | TheCodeBuzz

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

UnabletoconfigureHTTPSendpointNoservercertificatewasspecified | Hosting ASPNET Core API as Windows Service | TheCodeBuzz

Lets now execute the API routes below,

http://localhost:5050/WeatherForecast/

UnabletoconfigureHTTPSendpointNoservercertificatewasspecifiedurl | Hosting ASPNET Core API as Windows Service | TheCodeBuzz

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.


References:


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



  • Asrock 775twins hdtv драйвера windows 7
  • Asms windows xp при установке с флешки
  • Aspire one nav50 drivers windows 7
  • Asms windows xp sp3 скачать файл
  • Aspire e1 521 драйвера windows 7