[英]How to start and stop an ASP.NET Core 2.1 app programmatically with Windows Authentication enabled?
[英]Where can I log an ASP.NET Core app's start/stop/error events?
在舊的 ASP.NET 中,在Global.asax.cs
類中,我會記錄應用程序何時啟動、停止和拋出未處理的異常:
Application_Start()
Application_End()
Application_Error()
我如何在 ASP.NET Core 中做同樣的事情? 它有一個Startup
類,但它用於配置。
我在哪里掛鈎到應用程序的開始/停止/錯誤事件?
您需要使用Microsoft.AspNetCore.Hosting.IApplicationLifetime
/// <summary>
/// Triggered when the application host has fully started and is about to wait
/// for a graceful shutdown.
/// </summary>
CancellationToken ApplicationStarted { get; }
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// Requests may still be in flight. Shutdown will block until this event completes.
/// </summary>
CancellationToken ApplicationStopping { get; }
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// All requests should be complete at this point. Shutdown will block
/// until this event completes.
/// </summary>
CancellationToken ApplicationStopped { get; }
IApplicationLifetime 的實例可以在Configure
方法中獲得。 還要在這里添加 ILoggerFactory:
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
{
// use applicationLifetime
}
擁有ILoggerFactory
,您可以創建ILogger
實例:
var logger = loggerFactory.CreateLogger("StartupLogger");
所以你只需要在 Startup 類中創建一個屬性來持久化ILogger
的實例(或ILoggerFactory
,如果你想為不同的事件創建不同的 ligger 實例)。 總結一下:
public class Startup
{
private ILogger _logger;
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
{
applicationLifetime.ApplicationStopping.Register(OnShutdown);
...
// add logger providers
// loggerFactory.AddConsole()
...
_logger = loggerFactory.CreateLogger("StartupLogger");
}
private void OnShutdown()
{
// use _logger here;
}
}
請參閱CaptureStartupErrors和方法.CaptureStartupErrors(true)
,這將有助於你找到問題。
當某些東西在 localhost 上運行完美但在 Azure 中失敗時,這尤其方便。
這是我對 NetCore Web Apps 的常用配置:
public static IWebHost BuildWebHost(string[] args) => WebHost
.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>()
.UseAzureAppServices()
.Build();
在 Azure 應用服務中,您可以在 Kudu 工具的日志流中找到日志https://<appname>.scm.azurewebsites.net/api/logstream
我不喜歡@neustart47 的回答,因為它不必要地復雜,但他說IApplicationLifetime
已經過時是對的。
// 1. Add the interface `IHostedService` to the class you would like
// to be called during an application event.
internal class LifetimeEventsHostedService : IHostedService
{
private readonly ILogger _logger;
private readonly IHostApplicationLifetime _appLifetime;
// 2. Inject `IHostApplicationLifetime` through dependency injection in the constructor.
public LifetimeEventsHostedService(
ILogger<LifetimeEventsHostedService> logger,
IHostApplicationLifetime appLifetime)
{
_logger = logger;
_appLifetime = appLifetime;
}
// 3. Implemented by `IHostedService`, setup here your event registration.
public Task StartAsync(CancellationToken cancellationToken)
{
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStopping.Register(OnStopping);
_appLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
// 4. Implemented by `IHostedService`, setup here your shutdown registration.
// If you have nothing to stop, then just return `Task.CompletedTask`
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void OnStarted()
{
_logger.LogInformation("OnStarted has been called.");
// Perform post-startup activities here
}
private void OnStopping()
{
_logger.LogInformation("OnStopping has been called.");
// Perform on-stopping activities here
}
private void OnStopped()
{
_logger.LogInformation("OnStopped has been called.");
// Perform post-stopped activities here
}
}
完畢!
使用頂部答案中建議的Microsoft.AspNetCore.Hosting.IApplicationLifetime
現在已過時。
[Obsolete("This type is obsolete and will be removed in a future version. The recommended alternative is Microsoft.Extensions.Hosting.IHostApplicationLifetime.", false)]
public interface IApplicationLifetime
使用IHostApplicationLifetime
在應用程序關閉時觸發回調。
在某處添加:
public static async Task WaitForShutdownAsync(this IHost host)
{
// Get the lifetime object from the DI container
var applicationLifetime = host.Services.GetService<IHostApplicationLifetime>();
// Create a new TaskCompletionSource called waitForStop
var waitForStop = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
// Register a callback with the ApplicationStopping cancellation token
applicationLifetime.ApplicationStopping.Register(obj =>
{
var tcs = (TaskCompletionSource<object>)obj;
//PUT YOUR CODE HERE
// When the application stopping event is fired, set
// the result for the waitForStop task, completing it
tcs.TrySetResult(null);
}, waitForStop);
// Await the Task. This will block until ApplicationStopping is triggered,
// and TrySetResult(null) is called
await waitForStop.Task;
// We're shutting down, so call StopAsync on IHost
await host.StopAsync();
}
然后我在 Program.cs 中使用它:
var host = CreateHostBuilder(args).Build();
host.WaitForShutdownAsync();
其他回調也是如此。 您可以在此處找到更多信息
如果我錯過了什么,請告訴我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.