I'm experimenting with a Web API service. I'm trying to do a file download via a GET request. The method fires just fine and hits my break point. I create a response and return it. Then, oddly, the break point get hits again. I'm using the Firefox add-on Poster to test it. Poster says there's no response from the server. Any idea why that is happening?
Here's the response creation code:
HttpResponseMessage result = this.Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = file.Length;
result.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddDays(-1));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("Attachment") { FileName = file.Name };
return result;
The only significant change (I can think of) is to my WebApiConfig like so:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
My method signature looks like this: public HttpResponseMessage GetUpdate(int Id)
All my other actions are working fine. Am I missing something on the client side, like an accept header or something? I'm just doing a simple GET right now.
Thanks!
Found it! The using statement seems to be the trouble. The stream is probably being disposed of before the result can get sent. I updated my code like so and it started working:
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;
result.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddDays(-1));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("Attachment") { FileName = Path.GetFileName(filePath) };
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