我正在创建 ASP.NET Core 7 Web API,需要将其作为 Windows 服务托管运行。我已阅读文档但找不到解决方案。
我在我的
program.cs
中对此进行了测试,但我在事件查看器中看到了此错误:
由于以下错误,“我的服务”服务无法启动:
服务没有及时响应启动或控制请求。
builder.Services.AddWindowsService();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
if (OperatingSystem.IsWindows())
{
app.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStarted.Register(() =>
{
ServiceBase.Run(new ServiceBase[] { new MyWindowsService(app) });
});
}
else
{
app.Run();
}
class MyWindowsService : ServiceBase
{
private readonly IHost _host;
public MyWindowsService(IHost host)
{
_host = host;
}
protected override void OnStart(string[] args)
{
_host.Start();
}
protected override void OnStop()
{
_host.Dispose();
}
}
我只需添加以下代码就解决了这个问题。
builder.Host.UseWindowsService();
所以,我的 Program.cs 类看起来像这样:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Host.UseWindowsService();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();