Search code examples
arraysasp.net-core-webapiasp.net-core-6.0

Call an api with byte array in .NET 6


I am creating an ASP.NET Core 6 Web API. I did enable Swagger and would like to test an endpoint with input body of datatype byte[].

[HttpPost(Name = "publishdata")]
public IActionResult Get([FromBody] byte[] data)
{    
    return Ok();
}

And in RegisterServices I registered BinaryConverter:

services.AddControllers()
    .AddNewtonsoftJson(ser =>
    {
        ser.SerializerSettings.Converters.Add(new BinaryConverter());
       
    });

In Swagger, the data type shows as string so I put in something like "11001101101101" and executed. I am getting the following error:

{
  "errors": {
    "": [
      "The supplied value is invalid."
    ],
    "data": [
      "The data field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "0HMU568RIL38Q:0000000D"
}

Can someone help me if there is any additional configuration that I need to add? Or am I doing correctly? I had the same API in .NET 4.8 and it was working fine.

I tried different ways of passing body, changed configuration.


Solution

  • I use System.Text.Json and custom a JsonConverter<T> then it works well,

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

    Models

    public class MyModel
        {
            [JsonConverter(typeof(ByteArrayConverter))]
            public byte[] data { get; set; }
        }
    

    endpoint

    [HttpPost(Name = "publishdata")]
            public IActionResult Get([FromBody] MyModel model)
            {
                string utfString = Encoding.UTF8.GetString(model.data, 0, model.data.Length);
               
                return Ok(utfString);
            }    
        }
    

    enter image description here

    Hope this simple demo can give you some help.