【发布时间】:2016-11-15 18:59:45
【问题描述】:
我正在构建 ASP.NET Core MVC 应用程序,我需要像以前在 Global.asax 中那样拥有 EndRequest 事件。
我怎样才能做到这一点?
【问题讨论】:
-
我认为这是来自stackoverflow.com/questions/35705830/…的重复
标签: c# asp.net-core asp.net-core-mvc
我正在构建 ASP.NET Core MVC 应用程序,我需要像以前在 Global.asax 中那样拥有 EndRequest 事件。
我怎样才能做到这一点?
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc
这就像创建一个中间件并确保它尽快在管道中注册一样简单。
例如:
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();
}
【讨论】: