private Task<string> InternalReadResponseStringAsync(int retries)
{
return Task.Factory.FromAsync<WebResponse>(webRequest.BeginGetResponse, webRequest.EndGetResponse, null)
.ContinueWith(task => ReadStringInternal(() => task.Result))
.ContinueWith(task =>
{
var webException = task.Exception.ExtractSingleInnerException() as WebException;
if (webException == null || retries >= 3)
return task;// effectively throw
var httpWebResponse = webException.Response as HttpWebResponse;
if (httpWebResponse == null ||
httpWebResponse.StatusCode != HttpStatusCode.Unauthorized)
return task; // effectively throw
var authorizeResponse = HandleUnauthorizedResponseAsync(httpWebResponse);
if (authorizeResponse == null)
return task; // effectively throw
return authorizeResponse
.ContinueWith(_ =>
{
_.Wait(); //throw on error
return InternalReadResponseStringAsync(retries + 1);
})
.Unwrap();
}).Unwrap();
}
#endif