我正在构建 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'
// ...
}
}
调用await _next(context)
将导致管道中的所有中间件运行。所有中间件执行完毕后,将执行 await _next(context)
调用之后的代码。请参阅ASP.NET Core middleware docs有关中间件的更多信息。特别是文档中的这张图片使中间件执行变得清晰:
现在我们必须将其注册到 Startup
类中的管道,最好尽快:
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<EndRequestMiddleware>();
// Register other middelware here such as:
app.UseMvc();
}
关于c# - .NET Core EndRequest 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40604609/