2

I want to return a file in an HttpResponseMessage Content something like this:

return Request.CreateResponse(HttpStatusCode.OK, {{a file here}});

Or this:

return new HttpResponseMessage() {
   StatusCode = HttpStatusCode.OK; 
   Content = {{ a file "example.zip" here}}
};

Is this possible?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
  • See the following post, http://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api. That should probably give you some hints on how to proceed. – mattias Apr 17 '15 at 20:26

1 Answers1

4

You can use the System.Net.Http.HttpContent.StreamContent instance to add a FileStream object to the to the HttpResponseMessage's Content property. Something like this:

        // Return archive stream
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(fileStream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
            FileName = fileName.ToString()
        };

Note that you should probably also add a MD5 checksum to the file content in real applications.

Jeff Hay
  • 2,655
  • 28
  • 32
  • 3
    Hello, On the client side, how do get the filestream from the responsemessage?? Any idea? – Ronald Jul 09 '15 at 12:17