How to Get byte array properly from an Web Api Method in C#?

Actually, HTTP can handle “raw” binary as well – the protocol itself is text based, but the payload can be binary (see all those files you download from the internet using HTTP).

There is a way to do this in WebApi – you just have to use StreamContent or ByteArrayContent as the content, so it does involve some manual work:

public HttpResponseMessage ReturnBytes(byte[] bytes)
{
  HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
  result.Content = new ByteArrayContent(bytes);
  result.Content.Headers.ContentType = 
      new MediaTypeHeaderValue("application/octet-stream");

  return result;
}

It may be possible to do the same thing using some attribute or something, but I don’t know how.

Leave a Comment