简体   繁体   中英

How to host a .NET Core 3.1 API web application as windows service?

I have an existing .NET Core 3.1 API web application which I'd like to host as a windows service. What is the best way to achieve this?

I've found several tutorials stating that adding the nuget package Microsoft.Extensions.Hosting.WindowsServices and using the UseWindowsService() function should be enough to host it as windows service. 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.

I've also read about worker services but I have no idea how this would work with an existing API project.

My Program.cs looks like this:

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

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .Build();

            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls(config.GetSection("Hosting:Url").Value);
                    webBuilder.UseStartup<Startup>();
                }).UseWindowsService();
        }
    }

Regarding the 1053 error for .net core windows service, might be of help to others:

if the path to appsettings.json (or other external config files relative to base directory) is not correct, you get 1053

three things, in my case, affected the base directory path:

  1. the publish option Produce single file was checked
  2. started as a service from Services.exe (the same app, when opened as a console, had no problem)
  3. how you get the app base dir

For the third point, I don't remember exactly, especially since I found these things through trial and error, but the following code worked for me:

private static string GetBasePath()
{
    using var processModule = System.Diagnostics.Process.GetCurrentProcess().MainModule;
    return Path.GetDirectoryName(processModule?.FileName);
}

I'll try and test these things better when I have time and make it a little clearer

This is how I do it:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;

namespace App.Name.API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().RunAsService();
        }

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

I use CreateWebHostBuilder instead of Create WebHostBuilder since im more used to it (and unsure of the difference between the two).

I think that by downloading the Microsoft.Extensions.Hosting.WindowsServices package, and then adding UseWindowsService() at the end of CreateHostBuilder in Program.cs, then publishing will be the easiest way. (It should be your current plan.)

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

As for the error you are currently encountering, please refer to this document to resolve.

You can publish your application completely by reading this article and turn it into a windows service.(By reading this article, I successfully fulfilled your needs.)

There are two points to note.

When executing the cmd command, you need to right-click and select Run as Administrator , and then execute the sc command.

The executed command statement binPath and "=" can not have spaces, but the "=" and quotation marks must be separated, here is an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM