问题
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