Reputation: 8375
I received System.Threading.Tasks.TaskCanceledException
when making Http request.
public async Task<CommonResult<T>> GetRequest<T>(TokenModel token, string url)
{
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = int.MaxValue;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return await OK<T>(response);
}
else
{
//The response is authorized but some other error.
if (IsAuthorized(response.StatusCode))
return Error<T>(response.StatusCode.ToString());
//Unable to refresh token.
if (!await RenewToken(token))
return Error<T>("Fail to refresh token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(GlobalData.Token.TokenType, GlobalData.Token.AccessToken);
response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return await OK<T>(response);
}
else
{
return Error<T>(response.StatusCode.ToString());
}
}
}
}
It happens when I debug the server code and not continue. Is this natural behaviour or am I missing something in the client code?
Upvotes: 0
Views: 2663
Reputation: 5182
This is expected behaviour as by default HttpClient
sets a timeout of 100 seconds.
HttpClient Timeout
You can adjust on your HttpClient
and set a custom timeout duration. For example you can set an InfiniteTimeSpan
to prevent timeouts from occuring.
client.Timeout = Timeout.InfiniteTimeSpan;
HttpClient Request Timeout
You can additionally define a timeout per request using a CancellationTokenSource
using (var cts = new CancellationTokenSource(Timeout.InfiniteTimeSpan))
{
await client.GetAsync(url, cts.Token).ConfigureAwait(false);
}
Upvotes: 4