.NET Core EndRequest Middleware

杀马特。学长 韩版系。学妹 提交于 2020-01-13 03:54:09

问题


I'm builing ASP.NET Core MVC application and I need to have EndRequest event like I had before in Global.asax.

How I can achieve this?


回答1:


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. After all middleware has been executed, the code after the await _next(context) call will be executed. See the ASP.NET Core middleware docs for more information about middleware. 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:

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

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


来源:https://stackoverflow.com/questions/40604609/net-core-endrequest-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!