.NET Core 6 Web 应用程序关闭挂钩

问题描述 投票:0回答:1

在 C# .NET 6 Web 应用程序中使用 Serilog,在顶级启动代码中我有以下内容:

var logger = app.Services.GetService<ILogger<Program>>();
logger.LogInformation("The application has been initiated and is about to run");
app.Run();
logger.LogInformation("The application has been terminated");

我还在应用程序中进行了日志记录。除了

app.Run()
调用之后出现的那个之外,所有这些都有效。显然,当应用程序终止时,此后不会执行任何操作。我是否可以实现一个挂钩来触发应用程序的关闭,以便我可以记录终止事件?如果有什么不同,我会在 Visual Studio 中以在浏览器中自动打开的模式运行它,并在浏览器选项卡关闭时终止。

@AdamVincent:回复你的评论,这看起来确实是我一直在寻找的方法。但我尝试过

var logger = app.Services.GetService<ILogger<Program>>();
app.Lifetime.ApplicationStarted.Register(() => logger.LogInformation("The application has been initiated and is about to run."));
app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("The application is shutting down."));
app.Lifetime.ApplicationStopped.Register(() => logger.LogInformation("The application has terminated."));

app.Run();

结果:开始事件已被记录。其他两个事件没有。嗯。

.net-core serilog
1个回答
0
投票

我在另一个线程中找到了这个答案,ASP.NET Core - 注册应用程序关闭不起作用。简单来说,就是当应用程序在调试器中运行时,它会在浏览器关闭或单击“停止”按钮时突然终止。当我使用

dotnet run
运行它时,记录了 Stopping 和 Stopped 事件。另一方面,即便如此,在
app.Run()
调用之后的日志记录语句仍然没有运行,所以感谢 Adam Vincent 为我指出了钩子。

© www.soinside.com 2019 - 2024. All rights reserved.