为什么中间件组件在.NetCore管道中被调用两次?

c#

如果我创建一个空白的 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!");
    });
}

所以操作顺序是:

  1. 在第一个 app.Use() 中,调用了 await next.Invoke()
  2. 在第二个 app.Use() 中,等待 next.Invoke() 被调用
  3. App.Run() 被调用

然后,它通过管道返回..

  1. 在第二个 app.Use() 中,调用 int j = 0
  2. 在第一个 app.Use() 中,int i = 0 被调用

所有这一切都是预期的,因为它通过中间件并返回。但随后,再次重复上述每个步骤。

为什么每个中间件组件被调用两次?

回答

它被调用两次的原因是您的浏览器向您的应用程序发出两个请求。一个用于应用程序根路径 '/' 另一个用于 /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”路径


以上是为什么中间件组件在.NetCore管道中被调用两次?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>