Search code examples
azuremethodsdevopspoliciesapim

How to setup 405 Method Not Allowed for each of the methods in APIs using azure API Management


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?.


Solution

  • 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.