user2948533 user2948533 - 1 year ago 269
C# Question

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

I have the following controller method:

public byte[] MyMethod([FromBody] string ID)
byte[] mybytearray = db.getmybytearray(ID);//working fine,returning proper result.
return mybytearray;

Now in the calling method(thats also another WebApi method!) I have written like this:

private HttpClient client = new HttpClient ();
private HttpResponseMessage response = new HttpResponseMessage ();
byte[] mybytearray = null;
response = client.GetAsync(string.Format("api/ABC/MyMethod/{0}", ID)).Result;
if (response.IsSuccessStatusCode)
mybytearray = response.Content.ReadAsByteArrayAsync().Result;//Here is the problem

Now, the problem is the byte array
is sending is of 528 bytes, but here after making
, the size becomes larger(706 bytes) and the values are also goofed up.

Kind of banging my head against it, any help will be appreciated.


Answer Source

HTTP is a text based protocol. edit: HTTP can transport raw bytes as well. Luaan's answer is better.

The returned byte array will be converted into text in some way, depending on how the MediaTypeFormatterCollection is set up on the server and on the format requested by the HTTP client with the Accept header. The bytes will typically be converted to text by base64-encoding. The response may also be packaged further into JSON or XML, but the ratio of the expected length (528) to the actual length (706) seems to indicate a simple base64 string.

On the client side, you are not looking at the original bytes but at the bytes of this text representation. I would try reading the data as a string with ReadAsStringAsync and inspect it to see what format it is in. Also look at the headers of the response.

You should then parse this text accordingly to get the original bytes, e.g. with Convert.FromBase64String.