问题描述
我正在构建 ASP.NET Core MVC 应用程序,并且需要像以前在 Global.asax中进行的那样 EndRequest 事件.
I'm builing ASP.NET Core MVC application and I need to have EndRequest event like I had before in Global.asax.
我该如何实现?
推荐答案
创建中间件并确保尽快在管道中注册它就很容易.
It's as easy as creating a middleware and making sure it gets registered as soon as possible in the pipeline.
例如:
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'
// ...
}
}
对await _next(context)
的调用将导致所有中间件在管道中运行.执行完所有中间件后,将执行await _next(context)
之后的 调用代码.有关中间件的更多信息,请参见 ASP.NET Core中间件文档. .尤其是来自文档的此图像使中间件执行更加清晰:
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:
现在我们必须将其注册到Startup
类中的管道中,最好尽快注册:
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();
}
这篇关于.NET Core EndRequest中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!