In azure API Management how to setup the 405 (Method not allowed) policy. I am using azure API management APIs and adding different policies like jwt validation, IP filtering, rate limit and all. But I couldn't find a way for add the 405 method not allowed in APIM. I want to setup this for each of the methods. That means I want to block the incoming unrecognized method requests from APIM. (eg: Get instead of POST (Throws 405 method not allowed from APIM). Currently APIM passes the wrong method to backend and it returns the 404 from the application. Anyone know how we can block the wrong request from APIM side and returns 405 instead of passing it to backend and returns 404?.
Asked
Active
Viewed 1,098 times
1 Answers
0
You could use a Control Flow policy along with the Context Variable on the Inbound policy of each Method to intercept any requests that don't match the defined http method and then use a Set Status policy to return a 405. So for a GET method something along the lines of:
<policies>
<inbound>
<choose>
<when condition="@(context.Request.Method.ToString() != "GET")">
<return-response>
<set-status code="405" reason="No Content" />
</return-response>
</when>
</choose>
<base />
</inbound>
... rest of policies
</policies>
If you've got multiple methods with the same path you might need to apply this at the API level rather than the Method level and make the condition equals methods not in use rather than not equal to method in use
To set this at the API level and check against a collection of methods not in use create a policy along the lines of:
<policies>
<inbound>
<choose>
<when condition="@{
ICollection<string> disallowedMethods = new List<string>() { "POST", "PUT" };
return disallowedMethods.Contains(context.Request.Method.ToString());
}">
<return-response>
<set-status code="405" reason="No Content" />
</return-response>
</when>
</choose>
<base />
</inbound>
... rest of policies
</policies>
The http methods not in use in this example are POST and PUT but you can change the list to whatever applies in your use case.

Nick Graham
- 1,311
- 3
- 14
- 21
-
Hi Nick, Thanks much for your quick answer. I tried to implement this but I am thinking to implement this in API level because I have many methods in a single API and it is very complicated to add for each of them, For Azure APIM do you know how to create the condition that checks the URL and method is correct by comparing the existing methods in the list of methods in the API with the request method ? – Yadukrishnan P Jul 29 '20 at 17:50
-
@YadukrishnanP I don't think that's possible. I've added an example of how to do it with a static list of http methods but to dynamically check the existing methods you'd need to make an API call to get them. It doesn't look like there's a .NET Framework method available that would let you do that - https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions#CLRTypes – Nick Graham Jul 29 '20 at 20:23