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

如何在ASP.NET Core 7中用YARP搭建CORS Anywhere代理服务器?

解决方案

1. 删除冲突的控制器

你创建的GoogleMapsWebServiceController会优先拦截匹配/googlemapswebservice的请求,导致YARP代理无法处理该路径。必须删除这个控制器,让YARP的路由规则生效。

2. 修改YARP代理配置(appsettings.json)

要实现类似cors-anywhere的URL格式(代理地址后追加目标路径),并自动传递查询参数,需要调整路由匹配规则和路径转换逻辑:

"ReverseProxy": {
  "Routes": {
    "google-api-proxy": {
      "ClusterId": "google-api-cluster",
      "Match": {
        // 通配符匹配所有以/google-proxy开头的请求路径
        "Path": "/google-proxy/{**catch-all}"
      },
      "Transforms": [
        // 移除请求路径中的/google-proxy前缀,将剩余部分追加到目标地址后
        { "PathRemovePrefix": "/google-proxy" }
      ]
    }
  },
  "Clusters": {
    "google-api-cluster": {
      "Destinations": {
        "google-maps-api": {
          // 只保留Google APIs的根域名,后续路径由请求动态提供
          "Address": "https://maps.googleapis.com"
        }
      }
    }
  }
}

配置说明:

  • {**catch-all}:捕获/google-proxy之后的所有路径内容(包括多级路径)。
  • PathRemovePrefix:将请求路径中的/google-proxy前缀移除,确保转发到Google APIs的路径正确。
  • 集群地址改为https://maps.googleapis.com:避免原配置中路径重复拼接导致的404错误。

3. 配置CORS支持(解决Flutter Web跨域问题)

在ASP.NET Core中添加CORS策略,允许你的Flutter Web应用访问代理接口:

在ConfigureServices中添加:

services.AddCors(options =>
{
    options.AddPolicy("AllowFlutterWeb", policy =>
    {
        // 替换为你的Flutter Web实际运行地址(比如http://localhost:5003)
        policy.WithOrigins("http://your-flutter-web-url")
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

在Configure中启用CORS(需放在UseEndpoints之前):

app.UseCors("AllowFlutterWeb");

4. 验证代理请求

Flutter Web中只需将原Google APIs请求的前缀替换为你的代理地址即可:

  • 原请求:https://maps.googleapis.com/maps/api/place/autocomplete/json?input=xxx&key=xxx
  • 代理请求:http://your-proxy-server:5002/google-proxy/maps/api/place/autocomplete/json?input=xxx&key=xxx

此时YARP会自动:

  • 转发请求到对应的Google APIs接口
  • 传递所有查询参数
  • 处理CORS预请求(OPTIONS),避免前端跨域报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:47:40