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

编程入门 行业动态 更新时间:2024-10-27 13:22:25
本文介绍了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服务

本文发布于:2023-11-14 02:36:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585996.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   ASP   Core   Windows   Preview

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!