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

response.Content.ReadAsAsync<byte[]>().Result //Put this code in your client.

I want to make it clear that ReadAsAsync<byte[]>() and ReadAsByteArrayAsync() do NOT act the same.

ReadAsByteArrayAsync() turns everything into a Base64 Byte Array. It doesn't get the non-Base64 byte[] from response.Content but ReadAsAsync<byte[]>() does


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.