cva*_*app 15 c# asp.net hosting windows-services asp.net-core
我使用 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();
Run Code Online (Sandbox Code Playgroud)
我像这样发布了我的服务exe
dotnet publish -c Release -r win-x64 --self-contained
Run Code Online (Sandbox Code Playgroud)
Mic*_*oll 31
由于简单地使用
\nbuilder.Host.UseWindowsService();\nRun Code Online (Sandbox Code Playgroud)\n不适用于WebApplication.CreateBuilder()(请参阅),而是会抛出异常
\nException 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.\nRun Code Online (Sandbox Code Playgroud)\n或者更确切地说会导致这个错误
\nStart-Service : Service \'Service1 (Service1)\' cannot be started due to the following error: Cannot start service Service1 on computer \'.\'.\nRun Code Online (Sandbox Code Playgroud)\n当尝试使用Start-Service启动服务时,我找到了一个适合我的解决方法
\nusing Microsoft.Extensions.Hosting.WindowsServices;\n\nvar options = new WebApplicationOptions\n{\n Args = args,\n ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default\n};\n\nvar builder = WebApplication.CreateBuilder(options);\n\nbuilder.Host.UseWindowsService();\nRun Code Online (Sandbox Code Playgroud)\n\n
以下编码将生命周期设置为 WindowsServiceLifetime 并启用记录到事件日志。在大多数情况下,这应该是您将应用程序作为 Windows 服务运行所需的全部内容。
if (WindowsServiceHelpers.IsWindowsService())
{
appBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>();
appBuilder.Logging.AddEventLog(settings =>
{
if (string.IsNullOrEmpty(settings.SourceName))
{
settings.SourceName = appBuilder.Environment.ApplicationName;
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11747 次 |
| 最近记录: |