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

Azure API Management URI重写问题:如何在操作匹配前修改URI?

问题背景

客户端发起的请求URL为https://my-apim.azure-api.net/product/service1/v3/service1/operation,其中多了一个冗余的service1路径段。我的APIM基础URL是https://my-apim.azure-api.net/product/service1/,API版本为v3,目标操作路径是/operation。因为URL里多了这个service1,APIM无法匹配到对应的API操作,直接返回404。

之前我在API的入站策略里加了rewrite-uri规则试图移除多余的service1:

<rewrite-uri template="@(context.Request.OriginalUrl.Path.ToString().Replace("service1/operation", "operation"))" copy-unmatched-params="true" />

但这条规则根本没生效——通过调试跟踪发现,APIM的API和操作匹配步骤是在入站策略执行之前完成的,所以还没等到重写URI,就已经因为找不到操作返回404了。跟踪片段也显示API和版本匹配正确,但操作始终匹配失败:

{
    "source": "api-inspector",
    "timestamp": "2024-09-05T07:12:38.9153327Z",
    "elapsed": "00:00:00.0003329",
    "data": {
        "configuration": {
            "api": {
                "from": "/product/service1",
                "to": null,
                "version": "v3",
                "revision": "1"
            },
            "operation": "-",
            "user": "-",
            "product": {
                "id": "product"
            }
        }
    }
}
解决方案

核心思路是在APIM执行API/操作匹配之前修改请求URL,有两种可行方法:

方法1:用全局入站策略修正URL(推荐)

全局策略的执行时机早于API和操作匹配,能先把URL改对再让APIM做匹配:

  1. 登录APIM管理门户,进入「策略」>「全局策略」
  2. 编辑入站策略,添加以下规则:
<!-- 针对单个操作的精准匹配 -->
<rewrite-uri template="@(context.Request.OriginalUrl.Path.ToString().Replace("/v3/service1/operation", "/v3/operation"))" copy-unmatched-params="true" />

如果需要兼容多个操作,用更通用的写法:

<!-- 移除v3后的所有service1路径段 -->
<rewrite-uri template="@(context.Request.OriginalUrl.Path.ToString().Replace("/v3/service1/", "/v3/"))" copy-unmatched-params="true" />

方法2:修改API的URL模板兼容错误路径

如果不想改动全局策略,可以调整API的URL后缀,让它先匹配到错误的请求路径,再在入站策略里修正:

  1. 进入目标API的「设置」页面
  2. 将API的「URL后缀」从/product/service1修改为/product/service1/v3/service1
  3. 然后在该API的入站策略里添加重写规则,把路径修正为后端需要的格式:
<rewrite-uri template="/v3/operation" copy-unmatched-params="true" />

这种方法适合操作固定的场景,灵活性不如全局策略。

验证步骤

修改完成后重新发请求,通过APIM调试跟踪确认:

  • api-inspector阶段的operation字段不再是-,而是匹配到了目标操作
  • 后端最终收到的URL为https://server1.contoso.com/service1/operation,符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:57:23