You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多Razor Web应用YARP反向代理配置失效问题求助

解决YARP反向代理多Razor Web应用的路径配置问题

问题根源

你当前的YARP配置错误使用了PathPrefix转换,这会将匹配到的前缀追加到转发路径前,导致请求http://localhost:5000/web1/home被转发到http://localhost:5135/web1/home——但你的Razor应用根本没有/web1这个路由,自然无法正常响应。

正确配置方案

1. 修正YARP的路由转换配置

将Transforms中的PathPrefix替换为PathRemovePrefix,移除匹配到的前缀后再转发给目标应用:

"Yarp": {
  "Routes": {
    "web-route1": {
      "ClusterId": "web-cluster1",
      "Match": {
        "Path": "/web1/{**catch-all}"
      },
      "Transforms": [
        { "PathRemovePrefix": "/web1" }
      ]
    },
    "web-route2": {
      "ClusterId": "web-cluster2",
      "Match": {
        "Path": "/web2/{**catch-all}"
      },
      "Transforms": [
        { "PathRemovePrefix": "/web2" }
      ]
    }
  },
  "Clusters": {
    "web-cluster1": {
      "Destinations": {
        "destination1": {
          "Address": "http://localhost:5135/"
        }
      }
    },
    "web-cluster2": {
      "Destinations": {
        "destination1": {
          "Address": "http://localhost:5022/"
        }
      }
    }
  }
}

2. 配置Razor应用的路径基(关键步骤)

Razor应用默认以根路径/运行,如果不告知它自身的子路径,生成的页面链接、静态资源路径会直接指向代理的根路径(比如/home),导致跳转到http://localhost:5000/home而非http://localhost:5000/web1/home。

方法一:在Program.cs中设置PathBase

针对Web1应用,在启动代码中添加:

var builder = WebApplication.CreateBuilder(args);
// ... 其他服务配置

var app = builder.Build();

// 设置路径基
app.UsePathBase("/web1");
// ... 其他中间件配置(UseStaticFiles、UseRouting等)

app.Run();

Web2应用同理,设置app.UsePathBase("/web2")。

方法二:通过launchSettings.json配置(仅开发环境)

在Razor应用的Properties/launchSettings.json中,修改applicationUrl为带路径基的地址:

"profiles": {
  "Web1": {
    "commandName": "Project",
    "dotnetRunMessages": true,
    "launchBrowser": true,
    "applicationUrl": "http://localhost:5135/web1",
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    }
  }
}

3. 验证效果

启动YARP代理和两个Razor应用后,访问:

  • http://localhost:5000/web1 应正常显示Web1的首页
  • http://localhost:5000/web2 应正常显示Web2的首页
  • 页面内的链接、静态资源(CSS/JS)应自动带上/web1或/web2前缀,不会跳转到代理根路径

内容的提问来源于stack exchange,提问作者basilklochko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:20:20