ASP.NET Core 6 作为 Windows 服务托管

问题描述 投票:0回答:1

我目前在将 ASP.NET Core 6 作为 Windows 服务托管时遇到问题。我尝试过托管一个示例程序,它工作正常(代码粘贴在下面)。但是,如果我尝试更改端点或通过配置文件使用 kestrel 服务器来更改端点,我将无法将其托管为 Windows 服务。有人面临过类似的挑战吗?

我当前的工作示例类似于以下程序

var options = new WebApplicationOptions
            {
                Args = args,
                ContentRootPath = WindowsServiceHelpers.IsWindowsService()
                                     ? AppContext.BaseDirectory : default
            };

var builder = WebApplication.CreateBuilder(options);

builder.Services.AddRazorPages();
builder.Services.AddHostedService<Services.Worker>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

builder.Host.UseWindowsService();

var app = builder.Build();

app.UseRouting();
app.MapControllers();
app.Run();

工人服务看起来像这样:

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

    public ILogger Logger { get; }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Logger.LogInformation("Worker is starting.");

        stoppingToken.Register(() => Logger.LogInformation("Worker is stopping."));

        while (!stoppingToken.IsCancellationRequested)
        {
            Logger.LogInformation("Worker is doing background work.");

            await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
        }

        Logger.LogInformation("Worker has stopped.");
    }
}

但是,如果我尝试使用以下代码更改主程序中的端点,我将无法将其托管为 Windows 服务。

app.Urls.Add("http://localhost:5020");
app.Urls.Add("https://localhost:5021");

我的目标是将其作为 Windows 服务托管并使用证书进行身份验证。另外,我发现了一篇与 .NET 4.7 配合良好的博文:

https://rahulsahay19.medium.com/publishing-asp-net-core-as-windows-service-852fc2b930b8

有人尝试过使用证书进行身份验证、配置 URL 并将 ASP.NET Core 6 程序托管为 Windows 服务吗?

asp.net-core windows-services .net-6.0 windows-hosting
1个回答
0
投票

我能够通过自己生成证书并在配置文件中使用它来解决这个问题。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Kestrel": {
    "Endpoints": {
      "Localhost": {
        "Url": "https://localhost:5556",
        "ClientCertificateMode": "AllowCertificate",
        "Certificate": {
          "Path": "Certificate.pfx",
          "Password": "Password"
        }
      },
      "AnyIP": {
        "Url": "https://0.0.0.0:5557",
        "ClientCertificateMode": "AllowCertificate",
        "Certificate": {
          "Path": "Certificate.pfx",,
          "Password": "Password"
        }
      }
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.