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?
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.
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