在旧的ASP.NET,在Global.asax.cs类中,当应用程序启动、停止并抛出未处理的异常时,我会记录:

  • Application_Start()
  • Application_End()
  • Application_Error()

如何在ASP中实现同样的功能.净核心?它有一个Startup类,但它是用于配置的.

我应该在哪里挂接应用程序的启动/停止/错误事件?

推荐答案

注:适用于.NET Core 3.0或更高版本,此答案已过时.请看this answer.

你需要用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; }

Configure个方法中可以获得IApplicationLifetime的实例.另请在此处添加ILoggerFactory:

public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
{
    // use applicationLifetime
}

ILoggerFactory个,你就可以createILogger的实例:

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;
    }
}

Asp.net相关问答推荐

目前不支持超过 65534 个段的跨区存档

当前http上下文的http动词

SignalR + Autofac + OWIN:为什么 GlobalHost.ConnectionManager.GetHubContext 不起作用?

ASP.NET web api 无法获取 application/x-www-form-urlencoded HTTP POST

RestSharp 获取请求的完整 URL

如何在没有实体框架的情况下使用 ASP.NET Identity 3.0

如何将 global.asax 文件添加到 ASP.NET MVC4 项目?

从 RowDataBound 事件的 gridview 从单元格中获取值

使用 JavaScript 禁用 ASP.NET 验证器

你如何确定哪个验证器失败了?

尽管安装了 AspNetCoreModule,但在 IIS 中运行 ASP.NET Core 应用程序时出现 0x8007000d 错误 500.19

在 ASP.NET 4.5 WebForms 中通过 bundle.config 与 BundleConfig.cs Bundle 资源

如何确定服务器端 C# 上的浏览​​器窗口大小

svg 无法在 localhost 上的 IIS 网络服务器上运行

错误请求 - 无效的主机名 ASP.net Visual Studio 2015

System.Reflection.Assembly.LoadFile 锁定文件

System.Linq.IQueryable 不包含Where的定义

ASP.NET MVC 5 Web.config:FormsAuthenticationModule或FormsAuthentication

RegisterStartupScript 不适用于 ScriptManager、Updatepanel.这是为什么?

ASP.NET 邮箱验证器正则表达式