我想根据请求正文中的 mailTo
属性对 Lime 进行评级。
这是 APIM 政策
<rate-limit-by-key calls="5"
renewal-period="10"
counter-key="@(context.Request.Body.As<JObject>()["mailTo"].ToString())" />
这是请求正文
{
"mailTo": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="224f5b474f434b4e62454f434b4e0c414d4f" rel="noreferrer noopener nofollow">[email protected]</a>"
}
这对于直接调用后端来说工作正常,但在调用 APIM 时出现以下错误
{
"errors": {
"": [
"A non-empty request body is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-......-3be881755d918044-00"
}`
<rate-limit-by-key calls="5"
renewal-period="10"
counter-key="@(context.Request.Body.As<JObject>()["mailTo"].ToString())" />
最佳答案
我想该政策中有更多逻辑。
这个简单的策略不会产生上述错误:
<policies>
<inbound>
<base />
<rate-limit-by-key calls="5" renewal-period="10" counter-key="@(context.Request.Body.As<JObject>()["mailTo"].ToString())" />
<return-response>
<set-status code="200" reason="Ok" />
<set-body>{
"message": "It's fine!"
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
但我猜想请求正文在策略中至少使用了两次。
因此您必须设置参数 preserveContent
至true
:
context.Request.Body.As<JObject>(true)["mailTo"].ToString()
https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions
To avoid that and have the method operate on a copy of the body stream, set the preserveContent parameter to true
两次使用请求的策略:
<policies>
<inbound>
<base />
<rate-limit-by-key calls="5" renewal-period="10" counter-key="@(context.Request.Body.As<JObject>(true)["mailTo"].ToString())" />
<set-variable name="email" value="@(context.Request.Body.As<JObject>(true)["mailTo"]?.ToString().ToLower())" />
<return-response>
<set-body template="none">@{
var jsonResponse = new JObject();
jsonResponse.Add(new JProperty("message", (string)context.Variables["email"]));
return jsonResponse.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
关于Azure API 管理速率限制(按 Json 请求正文),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76943125/