使用 ASP.NET Core 6 Minimal API 在 Azure 中停止 Web 应用程序时未调用 BackgroundService StopAsync

Posted

技术标签:

【中文标题】使用 ASP.NET Core 6 Minimal API 在 Azure 中停止 Web 应用程序时未调用 BackgroundService StopAsync【英文标题】:BackgroundService StopAsync not called when stopping Web App in Azure using ASP.NET Core 6 Minimal API 【发布时间】:2022-01-20 03:58:23 【问题描述】:

我使用 VS 2022 ASP.NET 6.0 创建了模板 Minimal API 模板,并将 BackgroundService 添加为 HostedService。我将它部署到 Azure,它可以正常启动后台服务,我可以在日志中看到它。

但是,当我在 Azure 中停止 Web 应用程序时,不会调用 BackgroundService 的 StopAsync。我需要将 Program.cs 中的某些内容与 builder.Host 挂钩吗?如果我需要进行其他正常关闭,我如何在代码中收到 Web 应用程序正在关闭的通知?

Program.cs

using MinAPI.Test.Workers;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddHostedService<Worker>();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();

var summaries = new[]

    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
;

app.MapGet("/weatherforecast", () =>

    var forecast = Enumerable.Range(1, 5).Select(index =>
       new WeatherForecast
       (
           DateTime.Now.AddDays(index),
           Random.Shared.Next(-20, 55),
           summaries[Random.Shared.Next(summaries.Length)]
       ))
        .ToArray();
    return forecast;
)
.WithName("GetWeatherForecast");

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)

    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

Worker.cs

namespace MinAPI.Test.Workers

    public class Worker : BackgroundService
    
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        
            _logger = logger;
        

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        
            while (!stoppingToken.IsCancellationRequested)
            
                _logger.LogInformation("Worker running at: time", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            

            _logger.LogInformation("Worker cancellation token finished ");
        

        public override Task StartAsync(CancellationToken cancellationToken)
        
            _logger.LogWarning("Worker STARTING");
            return base.StartAsync(cancellationToken);
        

        public override Task StopAsync(CancellationToken cancellationToken)
        
            _logger.LogWarning("Worker STOPPING: time", DateTimeOffset.Now);
            return base.StopAsync(cancellationToken);
        
    

【问题讨论】:

【参考方案1】:

使用你的代码进行测试,发现只能重现一次你的错误,和你的截图一模一样。

然后我尝试重新部署它,我发现它消失了。下面的日志在我这边。

2021-12-20 05:48:53.068 +00:00 [Information] Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager: Azure Web Sites environment detected. Using 'C:\home\ASP.NET\DataProtection-Keys' as key repository; keys will not be encrypted at rest.
2021-12-20 05:48:54.116 +00:00 [Warning] dotnet5.Worker: Worker STARTING
2021-12-20 05:48:54.137 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:54 +00:00
2021-12-20 05:48:55.148 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:55 +00:00
2021-12-20 05:48:56.164 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:56 +00:00
2021-12-20 05:48:56.364 +00:00 [Information] Microsoft.Hosting.Lifetime: Application started. Press Ctrl+C to shut down.
2021-12-20 05:48:56.364 +00:00 [Information] Microsoft.Hosting.Lifetime: Hosting environment: Production
2021-12-20 05:48:56.364 +00:00 [Information] Microsoft.Hosting.Lifetime: Content root path: C:\home\site\wwwroot
2021-12-20 05:48:56.674 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request starting HTTP/1.1 GET https://test.azurewebsites.net/
2021-12-20 05:48:57.163 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:57 +00:00
2021-12-20 05:48:57.329 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executing endpoint 'dotnet5.Controllers.HomeController.Index (dotnet5)'
2021-12-20 05:48:57.724 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Route matched with action = "Index", controller = "Home", page = "", area = "". Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller dotnet5.Controllers.HomeController (dotnet5).
2021-12-20 05:48:57.852 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executing action method dotnet5.Controllers.HomeController.Index (dotnet5) - Validation state: Valid
2021-12-20 05:48:57.872 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action method dotnet5.Controllers.HomeController.Index (dotnet5), returned result Microsoft.AspNetCore.Mvc.ViewResult in 2.9601ms.
2021-12-20 05:48:58.054 +00:00 [Information] Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor: Executing ViewResult, running view Index.
2021-12-20 05:48:58.178 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:58 +00:00
2021-12-20 05:48:59.195 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:48:59 +00:00
2021-12-20 05:48:59.534 +00:00 [Information] Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor: Executed ViewResult - view Index executed in 1609.7136ms.
2021-12-20 05:48:59.544 +00:00 [Information] Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Executed action dotnet5.Controllers.HomeController.Index (dotnet5) in 1808.7693ms
2021-12-20 05:48:59.552 +00:00 [Information] Microsoft.AspNetCore.Routing.EndpointMiddleware: Executed endpoint 'dotnet5.Controllers.HomeController.Index (dotnet5)'
2021-12-20 05:48:59.583 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request finished in 2937.7265ms 200 text/html; charset=utf-8
2021-12-20 05:49:00.210 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:00 +00:00
2021-12-20 05:49:01.226 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:01 +00:00
2021-12-20 05:49:02.242 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:02 +00:00
2021-12-20 05:49:03.257 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:03 +00:00
2021-12-20 05:49:04.273 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:04 +00:00
2021-12-20 05:49:05.288 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:05 +00:00
2021-12-20 05:49:06.304 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:06 +00:00
2021-12-20 05:49:07.319 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:07 +00:00
2021-12-20 05:49:08.335 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:08 +00:00
2021-12-20 05:49:09.351 +00:00 [Information] dotnet5.Worker: Worker running at: 12/20/2021 05:49:09 +00:00
2021-12-20 05:49:09.820 +00:00 [Information] Microsoft.Hosting.Lifetime: Application is shutting down...
?2021-12-20 05:49:09.843 +00:00 [Warning] dotnet5.Worker: Worker STOPPING: 12/20/2021 05:49:09 +00:00
SnapshotUploader.exe Information: 0 : SnapshotUploader version 1.3.7.5 (x86) started.DateTime=2021-12-20T05:49:00.1939386ZSnapshotUploader.exe Information: 0 : Previous log file moved to C:\home\LogFiles\SnapshotUploader_c01540_20211220_054724.logDateTime=2021-12-20T05:49:00.1939386Z
SnapshotUploader.exe Information: 0 : Using AI ingestion endpoint: https://centralus-2.in.applicationinsights.azure.com//v2/trackDateTime=2021-12-20T05:49:00.2407520ZSnapshotUploader.exe Information: 0 : Using endpoint: https://agent.azureserviceprofiler.net/DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : [PII]Using iKey: a131ce6d-e7f6-451e-8f0c-2db3f2ad0bf0DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : Snapshot feature version: 1.0.0DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : Enabling site extension version: 3.13.2110.1201DateTime=2021-12-20T05:49:00.2563780ZSnapshotUploader.exe Information: 0 : Monitoring process 21104 for exit.DateTime=2021-12-20T05:49:00.4751823ZSnapshotUploader.exe Information: 0 : Scanning C:\home\site\wwwroot for local PDBs.DateTime=2021-12-20T05:49:03.4908425ZSnapshotUploader.exe Information: 0 : Scanning C:\Program Files (x86)\SiteExtensions\DiagnosticServices\3.13.2110\components\SnapshotCollector\1.3.7.5\core\netcoreapp3.0 for local PDBs.DateTime=2021-12-20T05:49:03.5065455ZSnapshotUploader.exe Information: 0 : Local PDB scan complete. Found 2 PDB(s).DateTime=2021-12-20T05:49:03.5065455ZSnapshotUploader.exe Information: 0 : Snapshot uploader successfully started. Using folder C:\local\Temp\Dumps\a131ce6de7f6451e8f0c2db3f2ad0bf0 for dump files.DateTime=2021-12-20T05:49:03.5377240ZSnapshotUploader.exe Information: 0 : SnapshotHolder listening on named pipe SnapshotUploader/ffa525a65d956d1f737e0e7e214c68deDateTime=2021-12-20T05:49:03.9127268ZSnapshotUploader.exe Information: 0 : Received Shutdown request from process 21104DateTime=2021-12-20T05:49:09.9786460ZSnapshotUploader.exe Information: 0 : Shutdown request from process 21104.DateTime=2021-12-20T05:49:09.9908695ZSnapshotUploader.exe Information: 0 : Stopped watching minidump folder. Draining snapshot holder queue.DateTime=2021-12-20T05:49:10.0065465ZSnapshotUploader.exe Information: 0 : Snapshot uploader exiting.DateTime=2021-12-20T05:49:10.0377999ZSnapshotUploader.exe Information: 0 : SnapshotHolder server exiting due to cancelation.DateTime=2021-12-20T05:49:10.0533711Z
2021-12-20T05:49:15 sandboxproc.exe D:\DWASFiles\Sites\#1test\Temp\applicationhost.config False True
2021-12-20T05:49:15 env XPROC_TYPENAME=Microsoft.Web.Hosting.Transformers.ApplicationHost.SiteExtensionHelper, Microsoft.Web.Hosting, Version=7.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
2021-12-20T05:49:15 env XPROC_METHODNAME=Transform
2021-12-20T05:49:16 Start 'Microsoft.AspNetCore.AzureAppServices.SiteExtension' site extension transform
2021-12-20T05:49:16 Successful 'C:\home\SiteExtensions\Microsoft.AspNetCore.AzureAppServices.SiteExtension\scmApplicationHost.xdt' site extension transform
2021-12-20T05:49:16 sandboxproc.exe complete successfully. Elapsed = 318.00 ms
2021-12-20T05:51:15  No new trace in the past 1 min(s).
2021-12-20T05:52:15  No new trace in the past 2 min(s).
2021-12-20T05:53:15  No new trace in the past 3 min(s).

所以我认为您的代码是正确的。我这边的测试代码和你一样。

【讨论】:

感谢您的浏览。有趣的是你是如何得到 Worker 的:STOPPING;我已经运行了几次,甚至一次都没有收到该消息!那么,我想,也许这是我需要在 .NET Core github 问题上发布的问题

以上是关于使用 ASP.NET Core 6 Minimal API 在 Azure 中停止 Web 应用程序时未调用 BackgroundService StopAsync的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core 6 Minimal API

使用 ASP.NET Core 6 Minimal API 在 Azure 中停止 Web 应用程序时未调用 BackgroundService StopAsync

创建API服务最小只要4行代码!!!尝新体验ASP.NET Core 6预览版本中的最小Web API(minimal APIS)新特性

ChatGPT Plugin 插件开发:基于 ASP.NET Core Minimal API

ASP NET Core Minimal API 总是返回 200 而不是指定的 204

在 ASP.NET Core 6.0 中使用 Serilog