如何在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
相关产品推荐
相关产品推荐

