Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return byte[] from ASP.net MVC 4 WEB API controller

I have a controller method which returns byte[].

[ActionName("testbytes")]
public byte[] GetTestBytes() {
    var b = new byte[] {137, 80, 78, 71};
    return b;
}

when i hit the api, i get following result.

<base64Binary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">iVBORw==</base64Binary>

Also when i hit this api from custom HttpClient, i get 10 bytes as a response. Following is the code of custom HttpClient.

public async Task<byte[]> GetTestBytes() {
    var uri = "apiPath/testbytes";
    using (var client = new HttpClient())
    {
        var httpResponse = await client.GetAsync(uri, HttpCompletionOption.ResponseContentRead);
        if (httpResponse.IsSuccessStatusCode) {
            var bytes = await httpResponse.Content.ReadAsByteArrayAsync();
        }
        return bytes;
    }
    return null;
}

I am expecting 4 bytes while i am receiving 10 bytes in response.

like image 554
MARKAND Bhatt Avatar asked Apr 26 '26 01:04

MARKAND Bhatt


1 Answers

@Markand: When you are hitting API, the response returned will be wrapped by double quotes ("responsebodygoeshere")

So following byte array

var b = new byte[] {137, 80, 78, 71};

is serialized as "iVBORw=="

Due to this when calling httpResponse.Content.ReadAsByteArrayAsync(); you will get bytes representation of "iVBORw==" (which will be 10 bytes) and not for iVBORw==

Optionally you can read response content as string and then trim the quotes and then convert it to the byte[] (There may be better approach. :))

i.e. var response = httpResponse.Content.ReadAsStringAsync().Trim('"')

then call following method to get bytes

var bytesResponse =  Convert.FromBase64String(response);
like image 134
AviD Avatar answered Apr 28 '26 14:04

AviD