Vnu*_*uuk 4 c# asp.net-core-mvc asp.net-core
我正在构建ASP.NET Core MVC应用程序,我需要像以前在Global.asax中那样拥有EndRequest事件.
我怎么能做到这一点?
它就像创建中间件一样简单,并确保它在管道中尽快注册.
例如:
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'
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
调用await _next(context)
将导致管道中的所有中间件运行.执行完所有中间件后,await _next(context)
将执行调用后的代码.有关中间件的更多信息,请参阅ASP.NET Core中间件文档.特别是来自文档的这个图像使中间件执行变得清晰:
现在我们必须在Startup
课堂上将它注册到管道中,最好尽快:
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<EndRequestMiddleware>();
// Register other middelware here such as:
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)