0

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?

mohsinali1317
  • 4,255
  • 9
  • 46
  • 85
  • What is the content type Web Api is returning? – jorgonor Nov 11 '16 at 12:00
  • 1
    It's impossible to help since you don't post the client code that retrieves the array. Web API *doesn't* send binary data, it encodes them using Base64. The service code is also ... uncommon. [This question](http://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api) for example shows how you can use a `StreamResult` to return binary data and specify the correct content type. – Panagiotis Kanavos Nov 11 '16 at 12:04
  • You can return binary data directly using the [BinaryArrayContent](https://msdn.microsoft.com/en-us/library/system.net.http.bytearraycontent(v=vs.118).aspx) class. I'd reconsider this though - there are specialized classes for returing file contents and BLOBs. Objects though should be returned as *Json*, otherwise clients won't be able to use the service without decoding the bytes. – Panagiotis Kanavos Nov 11 '16 at 12:07

1 Answers1

1

With the given information I think it must have something to do with content negotiation. I can't tell 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 returning a stream that must not be modified by Web Api Content Negotation.

jorgonor
  • 1,679
  • 10
  • 16