.NET Core EndRequest中间件

编程入门 行业动态 更新时间:2024-10-24 18:26:37
本文介绍了.NET Core EndRequest中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在构建 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中间件

本文发布于:2023-11-05 09:50:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   NET   Core   EndRequest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!