Azure Function 不返回 405 响应

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

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

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

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

最佳答案

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

解决方案

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

code screenshot

完整的示例代码如下:

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

预期返回的状态代码:

Correct Output in Postman

关于Azure Function 不返回 405 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63356261/

相关文章:

python - "WARNING:tornado.access:405"停止来自 "localhost"和 "file://"源的 POST 时出错

c# - 错误: Azure B2C Create user by post method from web application

Azure Functions 触发器失败 : A listener for function was unable to start

azure - 使用 Terraform 和函数扩展版本 4 创建函数应用程序

python - 在 python Azure Functions 中自定义日志格式

google-apps-script - 尝试发送 POST 请求时,App 脚本发送 405 响应

azure - Ansible 字符串变量到 Terraform 列表(字符串)

azure - 邀请在 AD B2C 中创建的用户登录我的应用程序

powershell - 使用 powershell 更新 SSL 配置

c# - Web API Put Request 生成 Http 405 Method Not Allowed 错误