.NET Core EndRequest 中间件

11

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

我该如何实现这一点呢?


我认为这是从https://dev59.com/85Tfa4cB1Zd3GeqPS5Yb复制的。 - error505
1个回答

29

只需创建一个中间件并确保它尽早在管道中注册即可。

例如:

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 pipeline 现在我们需要将其注册到管道中,在 Startup 类中尽可能早地完成:
public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<EndRequestMiddleware>();

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

2
我不明白为什么它会在请求结束之前被调用? - Vnuuk
@Vnuuk 我已经更新了我的答案。我还建议你阅读有关中间件的文档 - Henk Mollema

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接