我的 asp net core api 项目遇到问题。我尝试实现一些基本检查(例如数据库连接),如果检查失败,我想正常关闭我的应用程序。
为此,我实现了该接口并将其添加为我的类 ( ) 的方法IHostedService中的 HostedService 。ConfigureServicesstartupservices.AddHostedService<MyService>();
MyService 的实现StartAsync目前看起来是这样的:
public Task StartAsync(CancellationToken cancellationToken){
applicationLifetime.StopApplication();
}
Run Code Online (Sandbox Code Playgroud)
该变量applicationLifetime是类型的IHostApplicationLifetime并且是从 DI-Service 注入的。我得到以下异常:
[15:58:42 FTL] Unable to start Kestrel.
System.Threading.Tasks.TaskCanceledException: A task was canceled.
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.BindAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
Unhandled exception. System.Threading.Tasks.TaskCanceledException: A task was canceled.
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.BindAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerImpl.StartAsync[TContext](IHttpApplication`1 application, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at …Run Code Online (Sandbox Code Playgroud)