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

如何在Azure API Management中校验POST操作的productId参数长度

实现方法

你可以通过Azure APIM的入站校验策略实现拦截需求,具体操作如下:

  • 登录Azure门户,进入你的API Management实例,在左侧菜单栏找到「API」选项,选中你配置的目标API,再选择对应的POST /product/check操作。
  • 进入操作的「设计」页,找到「入站处理」模块,点击代码编辑图标(</>)进入策略XML编辑界面。
  • 在<inbound>节点中添加校验逻辑,完整的策略示例如下:
<inbound>
    <base />
    <!-- 提取请求体中的productId值存入变量 -->
    <set-variable name="requestProductId" value="@(context.Request.Body.As<JObject>()["productId"].ToString())" />
    <choose>
        <!-- 判断productId长度是否超过8位 -->
        <when condition="@(context.Variables.GetValueOrDefault<string>("requestProductId").Length > 8)">
            <!-- 匹配规则直接返回错误,不转发到后端 -->
            <return-response>
                <set-status code="400" reason="Invalid Parameter" />
                <set-header name="Content-Type" exists-action="override">
                    <value>application/json</value>
                </set-header>
                <set-body>
                @{
                    return new {
                        error = "productId length exceeds limit",
                        message = "productId can not be longer than 8 characters"
                    }.ToString();
                }
                </set-body>
            </return-response>
        </when>
    </choose>
</inbound>
  • 保存策略配置,等待1~2分钟生效后即可发起测试验证:传入长度超过8位的productId,会直接收到上述配置的400错误响应,不会转发到后端服务。
补充说明
  • 如果你的接口允许productId为空,可在长度判断前新增判空逻辑,避免解析空值时报错。
  • 若接口支持非JSON格式的入参,可根据实际入参格式调整参数提取的逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:06:03