如果我创建一个空白的 ASP.net Web Core 应用程序,然后将 Startup.cs 中的 Configure() 方法替换为以下方法,则每个 Use() 和 Run() 操作都会调用两次。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int i = 0;
});
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int j = 0;
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
}
所以操作顺序是:然后,它通过管道返回..
所有这一切都是预期的,因为它通过中间件并返回。但随后,再次重复上述每个步骤。
为什么每个中间件组件被调用两次?
最佳答案
它被调用两次的原因是您的浏览器向您的应用程序发出两个请求。一个用于应用程序根路径“/”,另一个用于/favicon.ico(一些浏览器,如 chrome,默认情况下会发出 favicon 请求,截图如下)。您可以检查您的浏览器开发工具。
您还可以通过将调试日志放入 app.Use
来验证这一点。查看请求路径。例如
app.Use(async (context, next) =>
{
Debug.WriteLine(context.Request.Path.Value);
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int i = 0;
});
所以你的中间件设置运行了两次。一次用于根“/”,第二次用于“/favicon.ico”路径
关于c# - 为什么中间件组件在 .Net Core 管道中被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66620965/