c# - 为什么中间件组件在 .Net Core 管道中被调用两次?

标签 c# .net asp.net-core

如果我创建一个空白的 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!");
    });
}
所以操作顺序是:
  • 在第一个 app.Use() 中, await next.Invoke() 被调用
  • 在第二个 app.Use() 中,等待 next.Invoke() 被调用
  • App.Run() 被调用

  • 然后,它通过管道返回..
  • 在第二个 app.Use() 中,int j = 0 被称为
  • 在第一个 app.Use() 中,int i = 0 被称为

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

    最佳答案

    它被调用两次的原因是您的浏览器向您的应用程序发出两个请求。一个用于应用程序根路径“/”,另一个用于/favicon.ico(一些浏览器,如 chrome,默认情况下会发出 favicon 请求,截图如下)。您可以检查您的浏览器开发工具。
    Chrome Dev Tools (F12 or Ctr + Shift + I shortcut)
    您还可以通过将调试日志放入 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/

    相关文章:

    c# - .NET 1.1 使用具有可空类型的 Web 服务,该怎么办?

    c# - 虚拟目录中的 ASP.NET MVC

    c# - 我怎样才能处理一个对象

    asp.net - 如何在 ASP.NET vNext 中处理调试/发布配置转换

    asp.net-core - .Net5 vs .Net Core 3 我应该选择哪一个作为目标

    c# - 读取文件时拆分字符串并忽略一个字符串 LINQ

    c# - JSON.NET反序列化自定义日期格式

    c# - .NET 中 NSOperationQueue 的等价物

    c# - 替换字符串中的 Unicode 转义序列

    c# - 在 Asp.Net Core 解决方案发布时转换 app.config 文件?