Chaudhry Mohsin Ali Chaudhry Mohsin Ali - 1 year ago 101
C# Question

Byte array different from an Web Api Method in C#?

So I have a web api which returns a byte array like this

public byte[] Validate()
{
byte[] buffer = licensePackage.ToByteArray();
return buffer;
}


The thing is when I get it on client it is different size and different byte array, I googled and found this link helpful http://www.codeproject.com/Questions/778483/How-to-Get-byte-array-properly-from-an-Web-Api-Met.

But can I know why this happens? Also, what is an alternate way to send back that file contents from the server?

Answer Source

With the given information I think it must have something to do with content negotiation. I can't tell about the reason, but what I'm sure it's that there is a different approach to serve files behind a Web Api.

var response = Request.CreateResponse(HttpStatusCode.OK);
var stream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read);

response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return ResponseMessage(response);

With this solution, you serve the file contents returning an IHttpActionResult instance. And, returning a response with StreamContent you are conceptually returning an array of bytes that must not be modified by Web Api. Content negotiation is not going to alter anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download