1
votes

When a HTTP Trigger is defined for only POST, but the user tries to perform a GET on the same URL, Azure Functions returns a 404 rather than the expected 405.

What is the best way to return HTTP Status Code 405 in this scenario? (along with the required "Allow" header)

Of interest, APIM also currently returns 404 instead of 405 responses (https://feedback.azure.com/forums/248703-api-management/suggestions/32626496).

1
For history, seems this is a behavior of the framework, effectively by design. github.com/aspnet/Mvc/issues/388Noah Stahl

1 Answers

1
votes

I checked a lot of documents and blogs, but did not find a perfect solution. I have a solution, it looks a little stupid, but it works.

Solution

You can allow the use of get requests, and then judge it inside Function. If it is a get request, manually specify the 405 status code.

code screenshot

The complete sample code is as follows:

public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        if (req.Method == HttpMethods.Get) {
            var result = new ObjectResult("your message");
            result.StatusCode = StatusCodes.Status405MethodNotAllowed;
            return result;
        }
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}

The status code returned is expected:

Correct Output in Postman