【问题标题】:Azure Function doesn't return a 405 responseAzure 函数不返回 405 响应
【发布时间】:2020-12-01 00:08:59
【问题描述】:

如果仅为 POST 定义了 HTTP 触发器,但用户尝试对同一 URL 执行 GET,Azure Functions 会返回 404 而不是预期的 405。

在这种情况下返回 HTTP 状态代码 405 的最佳方式是什么? (连同所需的“允许”标题)

有趣的是,APIM 目前还返回 404 而不是 405 响应 (https://feedback.azure.com/forums/248703-api-management/suggestions/32626496)。

【问题讨论】:

标签: azure azure-functions http-status-code-405


【解决方案1】:

我查了很多文档和博客,但没有找到完美的解决方案。我有一个解决方案,它看起来有点愚蠢,但它确实有效。

解决方案

可以允许使用get请求,然后在Function里面判断。如果是get请求,手动指定405状态码。

完整的示例代码如下:

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);
    }
}

返回的状态码是预期的:

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 2021-04-23
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多