炫意html5
最早CSS3和HTML5移动技术网站之一

asp.net core 中间件执行问题

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

不知道什么原因

回答

上星期遇到这个问题,搜遍全网也没个结果,根据园友 @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是不一样的。

炫意HTML5 » asp.net core 中间件执行问题

Java基础教程Android基础教程