APIM policy not able to return custom response for 'Method Not Allowed'

Umair Syed 0 Reputation points
2023-04-11T11:30:15.89+00:00

I am trying to block the GET method on the operation that supports POST method. Here is the policy I am defining:

	

I have tried adding this condition on different levels including operation, api and product level but APIM is always returning 404 instead of my custom response. Here is a screengrab of the failed request in postman: User's image

And here is the successful request:
User's image

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,452 questions
{count} votes

1 answer

Sort by: Most helpful
  1. MuthuKumaranMurugaachari-MSFT 22,441 Reputation points Moderator
    2023-04-17T14:21:20.72+00:00

    Syed, Umair Ok, understood the problem and thanks for sharing the additional details. For your scenario, you can define an API with Operations that are supported (such as POST in your example). By default, if APIM couldn't find a matching operation (for verb and URL template), then it would return 404 NotFound. To override this behavior, you can add the following code snippet in All Operations so that 405 MethodNotFound is returned.

    <on-error>
            <base />
            <choose>
                <when condition="@(context.LastError.Source == "configuration" && context.Request.Url.Path == "/notallowed/resource")">
                    <return-response>
                        <set-status code="405" reason="Method not allowed" />
                        <set-body>@{
                            return new JObject(
                                new JProperty("status", "HTTP 405"),
                                new JProperty("message", "Method not allowed")
                            ).ToString();
                        }</set-body>
                    </return-response>
                </when>
                <otherwise />
            </choose>
        </on-error>
    

    Note, you need to replace context.Request.Url.Path with the actual URL path like /echo/resource (policy snippet reference: here) and this would return the error if no verb is defined for the path. I hope this helps with your question and let me know if you face any issues or have any questions.


    If you found the answer to your question helpful, please take a moment to mark it as "Yes" for others to benefit from your experience. Or simply add a comment tagging me and would be happy to answer your questions.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.