.NET Core EndRequest中间件

时间:2016-11-15 07:51:13

标签: c# asp.net-core asp.net-core-mvc

我正在构建 ASP.NET Core MVC 应用程序,我需要像 Global.asax中那样拥有 EndRequest 事件。

我怎么能做到这一点?

1 个答案:

答案 0 :(得分:7)

就像创建中间件并确保它在管道中尽快注册一样简单。

例如:

public class EndRequestMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        // Do tasks before other middleware here, aka 'BeginRequest'
        // ...

        // Let the middleware pipeline run
        await _next(context);

        // Do tasks after middleware here, aka 'EndRequest'
        // ...
    }
}

await _next(context)的调用将导致管道中的所有中间件运行。执行完所有中间件后,将执行 await _next(context)调用后的代码。有关中间件的更多信息,请参阅ASP.NET Core middleware docs。特别是来自文档的这个图像使中间件执行变得清晰: Middleware pipeline

现在我们必须将它注册到Startup类的管道中,最好尽快:

public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<EndRequestMiddleware>();

    // Register other middelware here such as:
    app.UseMvc();
}