Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following controller method:

[HttpPost] [Route("SomeRoute")] 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 MyMethod is sending is of 528 bytes, but here after making ReadAsByteArrayAsync, the size becomes larger(706 bytes) and the values are also goofed up.

like image 853
user2948533 Avatar asked May 27 '14 08:05

user2948533


People also ask

How do I get bytes from MemoryStream?

To get the entire buffer, use the GetBuffer method. This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned.

How do you get a byte from a string?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .

What is Bytearray C#?

In C#.Net, we can create an unsigned byte array by using byte, byte is used to store only positive values between the range of 0 to 255 (Unsigned 8 bits integer). It occupies 1-byte memory for each element, if array size is 10, it will take 10 bytes memory.


1 Answers

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.

like image 87
Luaan Avatar answered Oct 04 '22 00:10

Luaan