ASP.NET Core .NET 6 Preview 7 Windows Service(ASP.NET Core.NET 6 Preview 7 Windows服务)
问题描述
我使用Visual Studio2022预览版创建了一个新的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();
我这样发布了我的服务可执行文件
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:Windowssystem32" 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中使用start-Service启动服务时,我发现了一种适合我的解决方法
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
这篇关于ASP.NET Core.NET 6 Preview 7 Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ASP.NET Core.NET 6 Preview 7 Windows服务


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01