ASP.NET Core .NET 6 Preview 7 Windows 服务

cva*_*app 15 c# asp.net hosting windows-services asp.net-core

我使用 Visual Studio 2022 Preview 创建了一个新的 ASP.NET Core 项目,并尝试将其作为 Windows 服务运行。我下载了最新的 Microsoft.Extensions.Hosting.WindowsServices 包 (6.0.0-preview.7.21377.19)。

在线研究时,函数 .UseWindowsService() 进入 CreateHostBuilder 方法。但在新模板中,情况看起来有所不同。我不明白应该在新模板中调用 .UseWindowsService 。这是我当前的代码,看起来服务正在启动,但是当我浏览到 localhost:5000 时,它给了我 404 错误

using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Hosting.WindowsServices;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseWindowsService(); // <--- Added this line

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "MyWindowsService", Version = "v1" });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
        app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyWindowsService v1"));
}

app.UseAuthorization();

app.MapControllers();


app.Run();
Run Code Online (Sandbox Code Playgroud)

我像这样发布了我的服务exe

dotnet publish -c Release -r win-x64 --self-contained
Run Code Online (Sandbox Code Playgroud)

Mic*_*oll 31

由于简单地使用

\n
builder.Host.UseWindowsService();\n
Run Code Online (Sandbox Code Playgroud)\n

不适用于WebApplication.CreateBuilder()请参阅),而是会抛出异常

\n
Exception Info: System.NotSupportedException: The content root changed from "C:\\Windows\\system32\\" to "...". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.\n
Run Code Online (Sandbox Code Playgroud)\n

或者更确切地说会导致这个错误

\n
Start-Service : Service \'Service1 (Service1)\' cannot be started due to the following error: Cannot start service Service1 on computer \'.\'.\n
Run Code Online (Sandbox Code Playgroud)\n

当尝试使用Start-Service启动服务时,我找到了一个适合我的解决方法

\n
using Microsoft.Extensions.Hosting.WindowsServices;\n\nvar options = new WebApplicationOptions\n{\n    Args = args,\n    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default\n};\n\nvar builder = WebApplication.CreateBuilder(options);\n\nbuilder.Host.UseWindowsService();\n
Run Code Online (Sandbox Code Playgroud)\n

这里:\n使用“UseWindowsService”的 asp.net core Web api 应用程序报告错误 \xe2\x80\x9cSystem.NotSupportedException:内容根目录已更改。启动服务时不支持更改主机配置\xe2\x80\x9d

\n


Tho*_*ösi 3

以下编码将生命周期设置为 WindowsServiceLifetime 并启用记录到事件日志。在大多数情况下,这应该是您将应用程序作为 Windows 服务运行所需的全部内容。

if (WindowsServiceHelpers.IsWindowsService())
{
    appBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>();
    appBuilder.Logging.AddEventLog(settings =>
    {
        if (string.IsNullOrEmpty(settings.SourceName))
        {
            settings.SourceName = appBuilder.Environment.ApplicationName;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)