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

如何让Azure静态Web应用调用APIM中的多个API?

解决Azure静态Web应用调用APIM多个API的方案

针对你遇到的问题,无需将所有端点合并成一个大APIM API,以下是两种可行的解决思路:

方案一:静态Web应用自定义路由代理

利用Static Web App的staticwebapp.config.json配置自定义路由规则,给不同的APIM API分配独立的前端路由前缀,直接代理到对应的APIM API路径。

配置步骤:

  1. 在静态Web应用的根目录创建(或修改)staticwebapp.config.json文件
  2. 为每个APIM API添加路由规则,示例如下:
{
  "routes": [
    // 代理到APIM中路径前缀为/service1的API
    {
      "route": "/api-service1/{*path}",
      "rewrite": "/service1/{path}",
      "backend": {
        "url": "https://your-apim-instance.azure-api.net"
      }
    },
    // 代理到APIM中路径前缀为/service2的API
    {
      "route": "/api-service2/{*path}",
      "rewrite": "/service2/{path}",
      "backend": {
        "url": "https://your-apim-instance.azure-api.net"
      }
    },
    // 保留默认的/api路由,指向APIM中空后缀的API(如果需要)
    {
      "route": "/api/{*path}",
      "backend": {
        "url": "https://your-apim-instance.azure-api.net"
      }
    }
  ]
}
  1. 部署配置文件到静态Web应用后,前端即可通过以下方式调用对应API:
    • 调用APIM的/service1/my-endpoint → 前端请求https://your-static-app.com/api-service1/my-endpoint
    • 调用APIM的/service2/my-endpoint → 前端请求https://your-static-app.com/api-service2/my-endpoint

这种方式无需修改APIM配置,所有代理逻辑在静态Web应用侧完成,前端调用的是同源域名,天然解决CORS问题。

方案二:APIM代理API中转

在APIM中创建一个空URL后缀的代理API,通过APIM的策略根据请求路径动态转发到其他内部API。

配置步骤:

  1. 在APIM中创建一个空URL后缀的API(例如命名为StaticWebAppProxy)
  2. 为该API配置入站策略,通过路径匹配转发到对应API,示例策略:
<policies>
  <inbound>
    <base />
    <!-- 根据请求路径前缀转发到对应API -->
    <choose>
      <when condition="@(context.Request.Url.Path.StartsWith("/service1/"))">
        <!-- 重写路径并转发到ID为Service1API的APIM API -->
        <rewrite-url template="/service1/{remaining}" />
        <set-backend-service backend-id="Service1API" />
      </when>
      <when condition="@(context.Request.Url.Path.StartsWith("/service2/"))">
        <rewrite-url template="/service2/{remaining}" />
        <set-backend-service backend-id="Service2API" />
      </when>
      <!-- 其他API的匹配规则依次添加 -->
      <otherwise>
        <!-- 默认转发到原有的空后缀API -->
        <set-backend-service backend-id="DefaultEmptySuffixAPI" />
      </otherwise>
    </choose>
    <!-- 统一处理订阅密钥(如果需要) -->
    <set-header name="Ocp-Apim-Subscription-Key" exists-action="override">
      <value>@{return context.Request.Headers.GetValueOrDefault("Ocp-Apim-Subscription-Key", "your-default-subscription-key");}</value>
    </set-header>
  </inbound>
  <backend>
    <forward-request />
  </backend>
  <outbound>
    <base />
  </outbound>
  <on-error>
    <base />
  </on-error>
</policies>
  1. 将静态Web应用的后端链接指向这个代理API,前端即可通过https://your-static-app.com/api/service1/my-endpoint直接调用APIM中的Service1API端点。

这种方式的优势是转发逻辑集中在APIM侧,便于统一管理认证、限流等策略,适合需要对所有API应用统一规则的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:40:33