I created a FileResult : IHttpActionResult return type FileResult : IHttpActionResult webapi for my api calls. FileResult downloads the file from another URL and then returns the stream to the client.
My code initially had a using statement, as shown below:
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { try { HttpResponseMessage response; using (var httpClient = new HttpClient()) { response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new System.Net.Http.StreamContent( await httpClient.GetStreamAsync(this.filePath)) }; } return response; } catch (WebException exception) {...} }
However, this would periodically result in a TaskCanceledException . I know that if the HttpClient is deleted before the asynchronous call is completed, the status of the Task will be canceled. However, since I use the wait in: Content = new System.Net.Http.StreamContent(await httpClient.GetStreamAsync(this.filePath)) , which should prevent HttpClient from being deleted in the middle of the task completion.
Why is this task canceled? This is not due to a timeout, as this happened on the smallest requests and does not always happen on large requests.
When I removed the using statement, the code worked correctly:
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { try { HttpResponseMessage response; var httpClient = new HttpClient(); response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new System.Net.Http.StreamContent( await httpClient.GetStreamAsync(this.filePath)) }; return response; } catch (WebException exception) {...} }
Any idea why use caused the problem?
Rafi
source share