Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
What do you mean you expect 4 bytes? That is 4 bytes. tomeko.net/online_tools/base64.php?lang=en –  Aron Mar 18 at 13:03
    
yes. I should get 4 bytes i.e. 137, 80, 78, 71 –  MARKAND Bhatt Mar 18 at 13:04
1  
That IS 4 bytes. Base64 encoding encodes binary into printable characters, so it takes more than 4 bytes to store 4 bytes, in this case 10 bytes. –  Aron Mar 18 at 13:06
1  
@Aron. Why API returns response in Base64 encoding? Is there any way to stop this. –  MARKAND Bhatt Mar 19 at 5:08

1 Answer 1

up vote 1 down vote accepted

@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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.