Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.

How I can achieve this?

like image 632
Vnuuk Avatar asked Nov 15 '16 07:11

Vnuuk


People also ask

What are the middleware in .NET Core?

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.

How do I use multiple middleware in NET Core?

To configure multiple middleware, use Use() extension method. It is similar to Run() method except that it includes next parameter to invoke next middleware in the sequence.

Can we create custom middleware in .NET Core?

We can add middleware using app. UseMiddleware<MyMiddleware>() method of IApplicationBuilder also. Thus, we can add custom middleware in the ASP.NET Core application.

What is default middleware in .NET Core?

Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks when there is an error, and it is a key piece in how we authenticate and authorize a user to perform specific actions.


1 Answers

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: 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();
}
like image 64
Henk Mollema Avatar answered Oct 13 '22 05:10

Henk Mollema