.net-corewindows-servicesasp.net-core-webapiworker-service

How to add Web API to existing Windows Service


is there any way to add Web API to existing Windows Service application ? Like adding new port on which to listen for http requests.

Currently service start point is looking like this:

ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinService1() };   
System.ServiceProcess.ServiceBase.Run(ServicesToRun);  

Using .net 6.

I know there is also worker service provided by .net core if the former is not possible can i migrate existing project to worker service and then add Web API ? Thanks for any advice!


Solution

  • I figured out how to do it. So this is the steps:

    1. In project .csproj file Changed target project SDK

    <Project Sdk="Microsoft.NET.Sdk"> to <Project Sdk="Microsoft.NET.Sdk.Web>

    2. Changed base class of service

    WinService1: ServiceBase to WinService1: BackgroundService

    3. Changed application entry point like this

    using this example: https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/host-and-deploy/windows-service/samples/6.x/WebAppServiceSample

    ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinService1() };   
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    

    to

    var options = new WebApplicationOptions
    {
        Args = args,
        ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
    };
    
    var builder = WebApplication.CreateBuilder(options);
    builder.Services.AddRazorPages();
    builder.Services.AddHostedService<WinService1>();
    
    builder.Host.UseWindowsService();
    
    var app = builder.Build();
    
    
    app.UseStaticFiles();
    app.UseRouting();
    app.MapRazorPages();
    await app.Run();