tde*_*ean 6 asp.net-core-hosted-services ihostedservice .net-6.0
我有一个 API,其中包含一个使用 .Net 6 在 VS2022 中构建的 HostedService。
当我在本地运行时,该服务将按预期调用,并且一切正常,但部署后,该服务似乎无法启动。
我尝试了许多不同的配置,甚至尝试使用后台服务,但结果都是相同的。这是我的代码:
我有一个在 VS2019 .Net Core 3.1 中构建的现有应用程序,它有一个 HostedService 并且工作正常。我注意到,当我将 .Net Core 应用程序转换为 .Net 6 时,该服务在部署时并未启动,因此我决定构建一个小应用程序来尝试找出导致问题的原因。
程序.cs
using HostedServices.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((context, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(context.Configuration)
.Enrich.FromLogContext()
.Enrich.WithMachineName());
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddHostedService<MainService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Run Code Online (Sandbox Code Playgroud)
这是托管服务
namespace HostedServices.Services
{
public class MainService : IHostedService, IDisposable
{
private int executionCount = 0;
private readonly ILogger<MainService> _logger;
private Timer _timer;
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();
public MainService(ILogger<MainService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"Test Hosted Service Started {DateTime.Now}.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromMinutes(1));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_executingTask = DoWorkAsync(_stoppingCts.Token);
}
private async Task DoWorkAsync(CancellationToken token)
{
_logger.LogInformation(
"Doing work: {0}", DateTime.Now);
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
}
Run Code Online (Sandbox Code Playgroud)
一切在本地运行良好,但是当我部署它时,服务似乎没有启动,没有生成日志文件,而且我似乎找不到报告的任何错误。
有任何想法吗?
小智 0
我们遇到了同样的问题,并通过以下 IIS 设置解决了它:
| 归档时间: |
|
| 查看次数: |
6739 次 |
| 最近记录: |