本文介绍了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 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服务
发布评论