gpt4 book ai didi

c# - ASP.NET Core .NET 6 Preview 7 Windows 服务

转载 作者:行者123 更新时间:2023-12-04 17:13:09 26 4
gpt4 key购买 nike

我使用 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();
我像这样发布了我的服务 exe
dotnet publish -c Release -r win-x64 --self-contained

最佳答案

由于简单地使用

builder.Host.UseWindowsService();
不适用于 WebApplication.CreateBuilder() ( see ),但会抛出异常
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.
或者更确切地说会导致这个错误
Start-Service : Service 'Service1 (Service1)' cannot be started due to the following error: Cannot start service Service1 on computer '.'.
尝试使用 启动服务时启动服务在 PowerShell 中,我找到了一个对我有用的解决方法
using Microsoft.Extensions.Hosting.WindowsServices;

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

var builder = WebApplication.CreateBuilder(options);

builder.Host.UseWindowsService();
这里:
An asp.net core web api application, using "UseWindowsService", reports an error “System.NotSupportedException: The content root changed. Changing the host configuration is not supported ” when starting the service

关于c# - ASP.NET Core .NET 6 Preview 7 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69124310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com