Vnuuk Vnuuk - 25 days ago 10
C# Question

.NET Core EndRequest Middleware

I'm builing MVC6 application and I need to have EndRequest event like I had before in Global.asax.

How I can achieve this?

Answer

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 ExceptionMiddleware(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: Middleware pipeline

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();
}