我使用 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
http://localhost:5000/swagger/v1/swagger.json
吗? - Jason Pan