Azure API Management Rewrite URI策略:请求体格式修正求助
解决Azure API Management中请求体数组转字符串的问题
问题描述
已完成Azure APIM的Rewrite URI策略配置,成功从请求体提取insurer_id并重写后端URL为mybackend.com/api/relationship/deny/{insurer_id}。但POST请求后,请求体中的status_code字段为["Deny"]数组格式,需要修正为"Deny"字符串格式,同时保留其他字段内容。
当前请求体:
{ "insurer_id": "22112", "insurer_name": "Steve Rogers", "status_code": [ "Deny" ], "additionalComments": "This is a test" }
预期请求体:
{ "insurer_id": "22112", "insurer_name": "Steve Rogers", "status_code": "Deny", "additionalComments": "This is a test" }
当前策略导致实际请求体中status_code变为带转义的字符串"[\"Deny\"]",不符合预期。
问题原因
原策略中获取status_code时直接调用ToString()方法,将数组对象转为了包含方括号和引号的字符串形式,且未正确修改请求体的原始内容,导致传递给后端的请求体字段格式错误。
修正后的策略代码
<policies> <inbound> <base /> <!-- 读取请求体并转为JObject,preserveContent设为true确保后续可重复读取 --> <set-variable name="requestBody" value="@{ return context.Request.Body.As<JObject>(preserveContent: true); }" /> <!-- 提取insurer_id用于URL重写 --> <set-variable name="insurerId" value="@{ var body = (JObject)context.Variables["requestBody"]; return body["insurer_id"].Value<string>(); }" /> <!-- 修改requestBody中的status_code字段:从数组取第一个元素转为字符串 --> <set-variable name="modifiedBody" value="@{ var body = (JObject)context.Variables["requestBody"].DeepClone(); if (body["status_code"] is JArray statusArray && statusArray.Count > 0) { body["status_code"] = statusArray[0].Value<string>(); } return body; }" /> <!-- 重写后端URL --> <rewrite-uri template="@("/api/relationship/deny/" + context.Variables.GetValueOrDefault<string>("insurerId"))" copy-unmatched-params="false" /> <set-backend-service base-url="https://testbackend.azure-api.net" /> <!-- 将修改后的内容设置为新的请求体 --> <set-body>@{ return ((JObject)context.Variables["modifiedBody"]).ToString(Newtonsoft.Json.Formatting.None); }</set-body> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies>
关键修改说明
- 一次性读取请求体:将请求体读取为
JObject并存储到变量,避免多次调用As<JObject>可能导致的性能问题,同时确保内容可重复使用。 - 正确提取数组元素:判断
status_code是否为JArray类型,若存在则取第一个元素转为字符串,替换原字段值。 - 重新设置请求体:使用
set-body策略将修改后的JObject转为JSON字符串,覆盖原始请求体,确保后端收到格式正确的内容。 - 优化URL重写:若无需传递
denyReason参数可直接移除;若需要传递,应使用提取到的字符串值而非数组的ToString结果。
内容的提问来源于stack exchange,提问作者jkhan_prog
相关产品推荐
相关产品推荐

