我为api调用创建了一个FileResult : IHttpActionResult
webapi返回类型。 FileResult从另一个URL下载文件,然后将流返回给客户端。
最初我的代码有一个using
语句,如下所示:
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)
{...}
}
然而,这会间歇性地导致TaskCanceledException
。我知道如果在异步调用完成之前处理HttpClient,Task的状态将变为取消。但是,因为我在Content = new System.Net.Http.StreamContent(await httpClient.GetStreamAsync(this.filePath))
中使用等待,这应该可以防止HttpClient在任务完成过程中被丢弃。
为什么该任务被取消?这不是因为超时,因为这发生在最小的请求上,并且不会在大请求上发生。
当我删除using
语句时,代码正常工作:
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)
{...}
}
知道为什么使用会导致这个问题吗?
答案 0 :(得分:11)
我知道如果在异步调用完成之前处理了HttpClient,则任务的状态将更改为已取消。但是因为我使用了await:Content = new System.Net.Http.StreamContent(等待httpClient.GetStreamAsync(this.filePath)),它应该阻止HttpClient在任务完成过程中被处理掉。
但是这个任务做了什么?它得到了流。因此,您的代码最终会得到一个Stream
,当它关闭HttpClient
时,可能会或可能不会被完全读取。
HttpClient
专为重复使用(以及同时使用)而设计,因此我建议完全删除using
并将HttpClient
声明移至static
类成员。但是,如果要关闭并重新打开客户端,则应该能够在关闭HttpClient
之前将读取流完全打入内存中。
答案 1 :(得分:5)
我遇到了类似于Task Canceled异常的问题。如果您尝试捕获AggregateException
或在Exception
下方捕获所有WebException
块,您可能会发现它已经抓住它,但有一个例外,条目说明&#34;任务被取消&#34;
我做了一些调查,发现AggregateException
非常误导,如各种线索所述;
Setting HttpClient to a too short timeout crashes process
How can I tell when HttpClient has timed out?
Bug in httpclientgetasync should throw webexception not taskcanceledexception
我最终更改了我的代码以设置显式超时(从app.config文件中读取asyncTimeoutInMins
);
string jsonResponse = string.Empty;
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(Properties.Settings.Default.MyWebService);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.Timeout = new TimeSpan(0, asyncTimeoutInMins, 0);
HttpResponseMessage response;
response = await httpClient.GetAsync("/myservice/resource");
// Check the response StatusCode
if (response.IsSuccessStatusCode)
{
// Read the content of the response into a string
jsonResponse = await response.Content.ReadAsStringAsync();
}
else if (response.StatusCode == HttpStatusCode.Forbidden)
{
jsonResponse = await response.Content.ReadAsStringAsync();
Logger.Instance.Warning(new HttpRequestException(string.Format("The response StatusCode was {0} - {1}", response.StatusCode.ToString(), jsonResponse)));
Environment.Exit((int)ExitCodes.Unauthorised);
}
else
{
jsonResponse = await response.Content.ReadAsStringAsync();
Logger.Instance.Warning(new HttpRequestException(string.Format("The response StatusCode was {0} - {1}", response.StatusCode.ToString(), jsonResponse)));
Environment.Exit((int)ExitCodes.ApplicationError);
}
}
}
catch (HttpRequestException reqEx)
{
Logger.Instance.Error(reqEx);
Console.WriteLine("HttpRequestException : {0}", reqEx.InnerException.Message);
Environment.Exit((int)ExitCodes.ApplicationError);
}
catch (Exception ex)
{
Logger.Instance.Error(ex);
throw;
}
return jsonResponse;