发布:2023/12/7 15:25:13作者:大数据 来源:大数据 浏览次数:450
为什么要实现这个拓展方法呢?个人认为
MiddlewareOptions、Middleware、MiddlewareExtensions、MiddlewareServicesExtensions这四个是实现一个中间件的标配(除去简单到不行的那些中间件)
MiddlewareOptions给我们的中间件提供了一些可选的处理,提高了中间件的灵活性;
Middleware是我们中间件最最重要的实现;
MiddlewareExtensions是我们要在Startup的Configure去表明我们要使用这个中间件;
MiddlewareServicesExtensions是我们要在Startup的ConfigureServices去表明我们把这个中间件添加到容器中。
例子:MyNameMiddlewareOptions、MyNameMiddleware、MyNameMiddlewareExtensions、MyNameMiddlewareServicesExtensions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Startup { public void Configure(IApplicationBuilder app) { app.Use(async (context, next) => { <strong>// Do work that doesn't write to the Response.</strong> await next.Invoke(); <strong>// Do logging or other work that doesn't write to the Response.</strong> }); app.Run(async context => { await context.Response.WriteAsync("Hello from 2nd delegate."); }); } } |
注意加粗行,大体意思是,在next.Invoke前后,不要调用Response写入操作,这样会出现异常,或中止中间件执行(短路)
微软官方:警告
Warning
Don't call next.Invoke
after the response has been sent to the client. Changes to HttpResponse after the response has started throw an exception. For example, changes such as setting headers and a status code throw an exception. Writing to the response body after calling next
:
Content-Length
.HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.
相关参考文档:
http://www.codeisbug.com/Doc/2/51
https://www.cnblogs.com/axzxs2001/p/7482771.html
© Copyright 2014 - 2025 柏港建站平台 ejk5.com. 渝ICP备16000791号-4