首页 新闻 会员 周边

asp.net core 中间件执行问题

0
悬赏园豆:5 [已解决问题] 解决于 2021-10-15 08:45

app.Use(async(context, next) =>
{
Console.WriteLine("Middleware one start");
//调用下一个中间件
await next();
Console.WriteLine("Middleware one end");
});

        app.Use(async (context, next) =>
        {
            Console.WriteLine("Middleware two start");
            //调用下一个中间件
            await next();
            Console.WriteLine("Middleware two end------");
        });

问题是每次请求都会执行两次中间件
Middleware one start
Middleware two start
Middleware two end------
Middleware one end
Middleware one start
Middleware two start
Middleware two end------
Middleware one end

不知道什么原因

QT2019的主页 QT2019 | 初学一级 | 园豆:14
提问于:2020-03-13 11:22

建议改进一下排版,支持 markdown 语法

dudu 4年前

建议提供重现问题的示例代码,如果能放在 github 上就更好了

dudu 4年前

@dudu: https://github.com/changfutao/CFT.Demo/blob/master/CFT.Demo.Admin/Startup.cs

QT2019 4年前

@QT2019: 你请求的是哪个 url ?

dudu 4年前
< >
分享
最佳答案
1

上星期遇到这个问题,搜遍全网也没个结果,根据园友 @shine声 所述,总算得到点信息,知道是浏览器的问题了,当时猜想是不是浏览器是多线程或多进程,为了提高下载速度,同样的资源多次连接,但是换了三个浏览器,结果都是这样,只执行两次即重复一次,实在想不明白,也就算了。今天调试一个web app,突然明白咋回事了,那是因为:
对同一个URL,所有浏览器默认就是访问两次,为啥,一次是这个网址本身,还有一次是网站的ICON文件favicon.ico,是不是大吃一惊,没想到竟然这么容易!如下所示:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:60705/ - -
fail: Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer[2]
Connection ID "17509995357122068613", Request ID "80000088-0001-f300-b63f-84710c7967bb": An unhandled exception was thrown by the application.
System.InvalidOperationException: The response headers cannot be modified because the response has already started.
......
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:60705/favicon.ico - -
fail: Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer[2]
Connection ID "17509995357122068613", Request ID "80000089-0001-f300-b63f-84710c7967bb": An unhandled exception was thrown by the application.
System.InvalidOperationException: The response headers cannot be modified because the response has already started.
可以看到, Connection ID是一样的,但是Request ID是不一样的。

收获园豆:5
黑衫老腰 | 菜鸟二级 |园豆:208 | 2021-07-16 06:47
其他回答(2)
0

吧url,httpmethod, requestid都打印出来

czd890 | 园豆:14412 (专家六级) | 2020-03-13 12:58
0

这个情况是直接在浏览器上做get请求才有。换个postman来请求就不会出现重复请求的。
至于为什么,不懂=-=

shine声 | 园豆:202 (菜鸟二级) | 2020-12-02 16:16

果真是这样

支持(0) 反对(0) 黑衫老腰 | 园豆:208 (菜鸟二级) | 2021-07-09 02:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册