I want to rate lime based on the mailTo
attribute from the request body.
Here is the APIM policy
<rate-limit-by-key calls="5"
renewal-period="10"
counter-key="@(context.Request.Body.As<JObject>()["mailTo"].ToString())" />
Here is the request body
{
"mailTo": "[email protected]"
}
This work fine for direct call to backend, but getting below error while calling to 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())" />
2
Answers
I have used the same policy in below format and it worked as expected
Policy
Test Result
Trace
I guess there’s much more logic in the policy.
This simple policy does not produce the mentioned error:
But I guess that the request body is used at least twice in the policy.
Therefore you have to set the parameter
preserveContent
totrue
:context.Request.Body.As<JObject>(true)["mailTo"].ToString()
https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions
Policy which uses the request twice: