简体   繁体   English

.NET Core EndRequest中间件

[英].NET Core EndRequest Middleware

I'm builing ASP.NET Core MVC application and I need to have EndRequest event like I had before in Global.asax. 我正在构建ASP.NET Core MVC应用程序,我需要像以前在Global.asax中那样拥有EndRequest事件

How I can achieve this? 我怎么能做到这一点?

It's as easy as creating a middleware and making sure it gets registered as soon as possible in the pipeline. 它就像创建中间件一样简单,并确保它在管道中尽快注册。

For example: 例如:

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'
        // ...
    }
}

The call to await _next(context) will cause all middleware down the pipeline to run. await _next(context)的调用将导致管道中的所有中间件运行。 After all middleware has been executed, the code after the await _next(context) call will be executed. 执行完所有中间件 ,将执行await _next(context)调用的代码。 See the ASP.NET Core middleware docs for more information about middleware. 有关中间件的更多信息,请参阅ASP.NET Core中间件文档 Especially this image from the docs makes middleware execution clear: 特别是来自文档的这个图像使中间件执行变得清晰: 中间件管道

Now we have to register it to the pipeline in Startup class, preferably as soon as possible: 现在我们必须将它注册到Startup类中的管道,最好尽快:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM