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.
@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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With