如何从邮递员传递字节数组

Aru*_*ngh 6 .net postman asp.net-core webapi

我正在开发一个公共 API,用户将在参数中发送 byte[]。我已经实现了 API 方法并想要对其进行测试,但是如果我在邮递员中尝试,则无法发送字节[]。出现以下错误

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|e1896d86-412b7762126469ae.",
"errors": {
    "$": [
        "The JSON value could not be converted to System.Byte[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
    ]
}
Run Code Online (Sandbox Code Playgroud)

}

API方法参数

public IActionResult Upload(int clientId, string dtName, byte[] dtValues, bool append)
    {
 
}
Run Code Online (Sandbox Code Playgroud)

邮递员电话

在此输入图像描述

Ren*_*ena 6

首先,asp.net core不支持从body中发布多个参数,您需要将这些参数放入模型中,然后才能从body中发布它们。

然后,您所做的事情应该从查询中发布。但好像不支持byte[]from查询。

  1. 如果您使用JSON.NET,您可以 post clientIddtNamefrom appendquery和 post from body 如下所示(确保您的控制器使用 声明):dtValues[ApiController]

在此输入图像描述

  1. 如果使用System.Text.Json,withSytem.Text.Json字节数组 ( byte[]) 将被序列化为 base64 字符串。他们表示不会在github 问题byte[]中添加对序列化为数字数组的支持。

自定义 JsonConverter:

public class ByteArrayConverter : JsonConverter<byte[]>
{
    public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        short[] sByteArray = JsonSerializer.Deserialize<short[]>(ref reader);
        byte[] value = new byte[sByteArray.Length];
        for (int i = 0; i < sByteArray.Length; i++)
        {
            value[i] = (byte)sByteArray[i];
        }

        return value;
    }

    public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options)
    {
        writer.WriteStartArray();

        foreach (var val in value)
        {
            writer.WriteNumberValue(val);
        }

        writer.WriteEndArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

注册它:

services.AddControllers().AddJsonOptions(options =>
{
     options.JsonSerializerOptions.Converters.Add(new ByteArrayConverter());
}); 
Run Code Online (Sandbox Code Playgroud)

在邮递员中测试:

在此输入图像描述

顺便说一句,不确定您的场景是什么,如果您发布的字节数组类似于文件例如:图像或.doc或.xlx文件),您可以在参数之前使用IFormFile并添加。[FromForm]两者JSON.NETSystem.Text.Json支持 receive IFormFile,这里不需要自定义 JsonConverter :

[Route("Upload")]
public IActionResult Upload(int clientId, string dtName, [FromForm]IFormFile dtValues, bool append)
{
        return Ok();
}
Run Code Online (Sandbox Code Playgroud)

发布数据如下: 在此输入图像描述

如果您不想分别query 和 body 发布它们可以它们放入模型中并从 body 发布它们。

模型:

public class TestModel
{
    public int clientId { get; set; }
    public string dtName { get; set; }
    public byte[] dtValues { get; set; }
    public bool append { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在邮递员中发帖:

注意:如果您使用System.Text.Json,您仍然需要像上面我分享的选项 2 一样自定义 JsonConverter 。

在此输入图像描述