You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将int数组作为Body参数传入.NET Isolated V4 Azure HTTP函数

解决Azure Functions Isolated模式下直接接收整数数组请求体的问题

问题原因

Azure Functions Isolated Worker模式的[FromBody]特性默认不支持直接绑定int[]这类数组类型;同时若请求体是包含数组的嵌套对象(如{"ids": [1,2,3]}),直接反序列化为int[]也会因格式不匹配触发序列化错误。

解决方案:手动读取并反序列化请求体

无需创建包装类,直接读取请求流并反序列化为int[]即可,核心是确保请求体为纯JSON数组格式,同时正确处理请求流的位置。

完整代码示例

using System.Net;
using System.Text.Json;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

public class ArrayFunction
{
    private readonly ILogger _logger;

    public ArrayFunction(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<ArrayFunction>();
    }

    public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
    {
        // 重置请求流位置,避免因流已被读取导致反序列化失败
        req.Body.Position = 0;
        
        int[]? ids = null;
        try
        {
            ids = JsonSerializer.Deserialize<int[]>(req.Body);
        }
        catch (JsonException ex)
        {
            _logger.LogError(ex, "Failed to deserialize request body to int array");
            var errorResponse = req.CreateResponse(HttpStatusCode.BadRequest);
            errorResponse.WriteString("Invalid JSON array format. Please send a raw JSON array like [1,2,3]");
            return errorResponse;
        }

        // 业务逻辑处理
        var response = req.CreateResponse(HttpStatusCode.OK);
        response.WriteString($"Successfully received {ids?.Length ?? 0} integers: {string.Join(", ", ids ?? Array.Empty<int>())}");
        return response;
    }
}

测试步骤

  1. 在Postman中发起POST请求,URL指向本地函数地址
  2. 请求Body选择raw,格式设置为JSON
  3. 输入纯JSON数组内容:[1, 2, 3, 4]
  4. 添加请求头Content-Type: application/json
  5. 发送请求,即可正确接收并处理整数数组

补充说明

  • 若坚持使用[FromBody]特性,可自定义实现IFromBodyConversionFeature来支持数组类型,但手动读取流的方式更简洁,无需额外配置
  • 必须保证请求体为纯JSON数组,而非包含数组的嵌套对象,否则会触发序列化异常

内容的提问来源于stack exchange,提问作者usr12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:41:06