Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Web API method firing twice?

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!

like image 971
Doug Dawson Avatar asked Jun 05 '13 20:06

Doug Dawson


1 Answers

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) };
like image 85
Doug Dawson Avatar answered Nov 11 '22 05:11

Doug Dawson