在ASP.NET 5中注册应用程序事件的处理程序

Mis*_*pic 6 c# asp.net visual-studio asp.net-core

如果我想在我的ASP.NET应用程序中处理应用程序事件,我会在我的注册处理程序Global.asax:

protected void Application_BeginRequest(object sender, EventArgs e)
{ ... }
Run Code Online (Sandbox Code Playgroud)

Global.asax 已从ASP.NET 5中删除.如何处理此类事件?

tug*_*erk 3

ASP.NET 5 中为每个请求运行一些逻辑的方法是通过中间件。这是一个示例中间件:

public class FooMiddleware
{
    private readonly RequestDelegate _next;

    public FooMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // this will run per each request
        // do your stuff and call next middleware inside the chain.

        return _next.Invoke(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的班级中注册它Startup

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseMiddleware<FooMiddleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

有关ASP.NET 5 中的中间件的更多信息,请参阅此处。

对于任何应用程序启动级别调用,请参阅应用程序启动文档