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

如何在Azure APIM策略中移除URI路径中的指定部分?

Azure APIM策略移除URI路径指定部分的解决方案

要移除请求URI路径中的/preprod部分,同时保留查询参数和其他路由信息,可以在现有策略的<when>分支中添加路径重写逻辑,具体实现如下:

修改后的完整策略代码

<policies>   
    <inbound>
        <base />
        <choose>
            <when condition="@(context.Request.OriginalUrl.Path.Contains("/preprod"))">
                <set-backend-service backend-id="pub-lb-api-v1" />
                <set-header name="Host" exists-action="override">
                    <value>test.abc.com</value>
                </set-header>
                <!-- 移除路径开头的/preprod部分,保留查询参数 -->
                <rewrite-uri template="@(System.Text.RegularExpressions.Regex.Replace(context.Request.OriginalUrl.Path, "^/preprod", ""))" copy-unmatched-params="true" />
            </when>
            <otherwise>
                <!-- 保留原有其他分支逻辑 -->
            </otherwise>
        </choose>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

关键逻辑说明

  • 路径重写:使用rewrite-uri策略配合正则替换^/preprod(仅匹配路径开头的/preprod),避免误删路径中间可能出现的相同字符串;替换后得到的新路径会自动应用到后端请求。
  • 保留查询参数:copy-unmatched-params="true"参数确保原请求的查询参数(如?xyz=1)会被完整保留并传递到新URL中。
  • 替代方案:如果偏好使用set-url策略,也可以用以下代码实现相同效果:
    <set-url>@(new UriBuilder(context.Request.OriginalUrl) { Path = System.Text.RegularExpressions.Regex.Replace(context.Request.OriginalUrl.Path, "^/preprod", "") }.ToString())</set-url>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 01:30:05