3

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.

4
  • What do you mean you expect 4 bytes? That is 4 bytes. tomeko.net/online_tools/base64.php?lang=en Commented Mar 18, 2015 at 13:03
  • yes. I should get 4 bytes i.e. 137, 80, 78, 71 Commented Mar 18, 2015 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. Commented Mar 18, 2015 at 13:06
  • 2
    @Aron. Why API returns response in Base64 encoding? Is there any way to stop this. Commented Mar 19, 2015 at 5:08

1 Answer 1

1

@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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.