升级到.NET 8/隔离工作模型更改http返回状态代码

问题描述 投票:0回答:1

我有以下函数(简化),它返回状态代码 404 和空正文的 http 响应:

[Function("GetItem")]
public async Task<IActionResult> GetItemAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = "GetItem/{id}")] HttpRequest request,
        string id,
        CancellationToken c)
{
    return new NotFoundResult();
}

它在 .NET 6 中按预期工作,并使用进程内模型在 Azure 函数上运行。

我正在将其升级到.NET 8和隔离的工作模型,现在响应状态代码为200,正文如下:

{
    "StatusCode": 404
}

我想知道是什么导致了这种行为变化以及如何解决它?当然,我不想将 http 状态包装在响应负载中。

azure azure-functions .net-8.0 azure-functions-isolated
1个回答
0
投票

我已按如下方式修改了您的代码,它按预期工作:

函数.cs:

public class Function1
{
    private readonly ILogger<Function1> _logger;

    public Function1(ILogger<Function1> logger)
    {
        _logger = logger;
    }
    private static readonly Dictionary<string, string> items = new Dictionary<string, string>
    {
    { "1", "Book 1" },
    { "2", "Book 2" },
    { "3", "Book 3" }
    };

    [Function("GetItem")]
    public async Task<IActionResult> GetItemAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = "GetItem/{id}")] HttpRequest request,
    string id,
    CancellationToken c)
    {
        _logger.LogInformation($"Received request for item with id: {id}");

        await Task.Delay(100, c);
        if (items.TryGetValue(id, out var item))
        {
            return new OkObjectResult(item);
        }
        else
        {
            return new NotFoundResult();
        }

    }
}

未找到项目时输出:

enter image description here

Functions:

        GetItem: [GET] http://localhost:7180/api/GetItem/{id}

For detailed output, run func with --verbose flag.
[2025-01-09T05:08:50.926Z] Host lock lease acquired by instance ID '000000000000000000000000F72731CC'.
[2025-01-09T05:08:51.930Z] Executing 'Functions.GetItem' (Reason='This function was programmatically called via the host APIs.', Id=8e5947ce-d529-4f67-b081-361404ed97f4)
[2025-01-09T05:08:52.208Z] Received request for item with id: 4
[2025-01-09T05:08:52.319Z] Executing StatusCodeResult, setting HTTP status code 404
[2025-01-09T05:08:52.382Z] Executed 'Functions.GetItem' (Succeeded, Id=8e5947ce-d529-4f67-b081-361404ed97f4, Duration=481ms)

找到物品时输出:

enter image description here

Functions:

        GetItem: [GET] http://localhost:7180/api/GetItem/{id}

For detailed output, run func with --verbose flag.
[2025-01-09T05:20:12.474Z] Host lock lease acquired by instance ID '000000000000000000000000F72731CC'.
[2025-01-09T05:20:14.715Z] Executing 'Functions.GetItem' (Reason='This function was programmatically called via the host APIs.', Id=81dd75a1-7167-4169-a3f0-8b4d88f13dc2)
[2025-01-09T05:20:15.015Z] Received request for item with id: 2
[2025-01-09T05:20:15.145Z] Executing OkObjectResult, writing value of type 'System.String'.
[2025-01-09T05:20:15.226Z] Executed 'Functions.GetItem' (Succeeded, Id=81dd75a1-7167-4169-a3f0-8b4d88f13dc2, Duration=537ms)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.