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?

3
  • What is the content type Web Api is returning? Commented Nov 11, 2016 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 for example shows how you can use a StreamResult to return binary data and specify the correct content type. Commented Nov 11, 2016 at 12:04
  • You can return binary data directly using the BinaryArrayContent 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. Commented Nov 11, 2016 at 12:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.