I have a program which does API call using HttpClient and overriding DelegatingHandler class to retry request on failure as shown below.
class TestHandler
{
public static void APICallTest()
{
var handler = new HttpClientHandler() { Credentials = CredentialCache.DefaultNetworkCredentials };
var client = new HttpClient(new RetryMessageHandler(handler));
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Clear();
client.Timeout = TimeSpan.FromSeconds(90);
client.DefaultRequestHeaders.Host = "lab.abc.xyz.def.net";
ServicePointManager.ServerCertificateValidationCallback
+= (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
for (int i = 0; i < 499; i++)
{
try
{
using (HttpResponseMessage res =
client.GetAsync("https://abc.xyz.def.net/rest/").Result)
{
if (res != null)
{
Console.WriteLine("response: " + res);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
public class RetryMessageHandler : DelegatingHandler
{
public RetryMessageHandler(HttpMessageHandler innerhandler):base(innerhandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
var exceptions = new List<Exception>();
for (int attempt = 0; attempt < 3; attempt++)
{
await Task.Delay(5 * attempt).ConfigureAwait(false);
try
{
response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
catch (System.Net.Http.HttpRequestException ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}
The program works with successful response from API. In 500 requests 2-3 requests fail with Forbidden 403. The unsuccessful API calls is random. The logs in API server show that the failed request had no Credentials.
Does anyone have idea on the reason for random failure? How do I check if Credentails is sent in every request?