【问题标题】:Why are Middleware Components Called Twice in a .Net Core Pipeline?为什么中间件组件在 .Net Core 管道中被调用两次?
【发布时间】:2021-03-14 04:01:23
【问题描述】:

如果我创建一个空白的 ASP.net Web Core Application,然后将 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

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

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

【问题讨论】:

    标签: c# .net asp.net-core


    【解决方案1】:

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

    【讨论】:

    • 这是一个关于我所经历的操作也可能是 aysnc 和等待的想法,(调试器在线程之间跳转)看起来像它的两次......但以上可能是原因。 OP需要检查网址
    猜你喜欢
    • 2020-05-08
    • 2017-01-22
    • 1970-01-01
    • 2021-04-27
    • 2020-04-28
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多