【问题标题】:.NET Core EndRequest Middleware.NET Core EndRequest 中间件
【发布时间】:2016-11-15 18:59:45
【问题描述】:

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

我怎样才能做到这一点?

【问题讨论】:

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


【解决方案1】:

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

例如:

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。尤其是文档中的这张图片使中间件的执行更加清晰:

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

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

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

【讨论】:

  • 不明白为什么会在请求结束前调用?
  • @Vnuuk 我已经更新了我的答案。我还建议您阅读docs about middleware
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 2018-06-28
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
相关资源
最近更新 更多