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?
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.
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.
We can add middleware using app. UseMiddleware<MyMiddleware>() method of IApplicationBuilder also. Thus, we can add custom middleware in the ASP.NET Core application.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With