Why does this Web API method fire twice?

I am experimenting with a web API service. I am trying to download a file using a GET request. The method works just fine and hits my break point. I create an answer and return it. Then, oddly enough, the breakpoint hits again. I am using the Firefox Add-on Poster to test it. The poster says there is no response from the server. Any idea why this is happening?

Here is 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 my WebApiConfig:

 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 the accept header or something else? I'm just doing a simple get right now.

Thanks!

+6
source share
1 answer

Found! Apparently the problem is using the operator. The thread is probably deleted before the result can be sent. I updated my code and 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) }; 
+5
source

Source: https://habr.com/ru/post/946624/


All Articles