MVC or Web API transfer byte[] the most efficient approach MVC or Web API transfer byte[] the most efficient approach arrays arrays

MVC or Web API transfer byte[] the most efficient approach


What is the correct way to pass a byte array

The easiest way of reading a byte[] from WebAPI without writing custom MediaTypeFormatter for "application/octet-stream" is by simply reading it from the request stream manually:

[HttpPost]public async Task<JsonResult> UploadFiles(){    byte[] bytes = await Request.Content.ReadAsByteArrayAsync();}

In another post, I described how to utilize the built in formatter for BSON (Binary JSON) which exists in WebAPI 2.1.

If you do want to go down the read and write a BinaryMediaTypeFormatter which answers "application/octet-stream", a naive implementation would look like this:

public class BinaryMediaTypeFormatter : MediaTypeFormatter{    private static readonly Type supportedType = typeof(byte[]);    public BinaryMediaTypeFormatter()    {        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));    }    public override bool CanReadType(Type type)    {        return type == supportedType;    }    public override bool CanWriteType(Type type)    {        return type == supportedType;    }    public override async Task<object> ReadFromStreamAsync(Type type, Stream stream,        HttpContent content, IFormatterLogger formatterLogger)    {        using (var memoryStream = new MemoryStream())        {            await stream.CopyToAsync(memoryStream);            return memoryStream.ToArray();        }    }    public override Task WriteToStreamAsync(Type type, object value, Stream stream,        HttpContent content, TransportContext transportContext)    {        if (value == null)            throw new ArgumentNullException("value");        if (!type.IsSerializable)            throw new SerializationException(                $"Type {type} is not marked as serializable");        var binaryFormatter = new BinaryFormatter();        binaryFormatter.Serialize(stream, value);        return Task.FromResult(true);    }}