首页 > 解决方案 > Yarp 反向代理 - 响应 502 错误网关

问题描述

我想使用 Yarp 实现反向代理。Api 已启动并正在运行,因为我可以向它发送请求。但是,每当我通过代理尝试相同的请求时,我都会收到错误 502 Bad gateway

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddReverseProxy()
     .LoadFromConfig(Configuration.GetSection("ReverseProxy"));
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseRouting();
    // Register the reverse proxy routes
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapReverseProxy();
    });
}

应用设置

"ReverseProxy": {
    "Routes": {
      "route1": {
        "ClusterId": "cluster1",
        "Match": {
          //"Methods": [ "GET", "POST", "PUT", "HEAD", "OPTIONS", "DELETE" ],
          "Path": "{**catch-all}"
        }
      }
    },
    "Clusters": {
      "cluster1": {
        "Destinations": {
          "cluster1/destination1": {
            "Address": "https://localhost:44339/"
          }
        }
      }
    }
  }

我收到响应 - 502 bad gateway 每当我通过代理发送请求时

标签: c#asp.net-coreasp.net-core-3.1yarp

解决方案


您应该单击output并选择ProjectName-Asp.Net Core Web Server以检查详细信息。

我使用您的代码并附加了另一个设置,并检查了日志,我发现原因是 http://localhost:44339 无法启动。它应该在本地使用另一个 webapp 的端口。

在此处输入图像描述

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  //"AllowedHosts": "*"

  "ReverseProxy": {
    "Routes": [
      {
        "ClusterId": "cluster1",
        "Match": {
          //"Methods": [ "GET", "POST", "PUT", "HEAD", "OPTIONS", "DELETE" ],
          "Path": "{**catch-all}"
        }
      },
      {
        // matches /something/* and routes to 2 external addresses
        "ClusterId": "cluster2",
        "Match": {
          "Path": "/something/{*any}"
        }
      }
    ],
  "Clusters": {
      "cluster1": {
        "Destinations": {
          "cluster1/destination1": {
            "Address": "http://localhost:44339/"
          }
        }
      },
      "cluster2": {
        "Destinations": {
          "first_destination": {
            "Address": "https://baidu.com"
          },
          "another_destination": {
            "Address": "https://bing.com"
          }
        },
        "LoadBalancingPolicy": "PowerOfTwoChoices"
      }

    }
  }
}

测试结果

默认:https://localhost:44370

在此处输入图像描述

https://localhost:44370/somthing

它将重定向到 bing 站点。

在此处输入图像描述


推荐阅读