Fixing issue with HTTPClient and Too many automatic redirections were attempted.



When you are trying to use Microsoft HTTPClient to perform HTTP requests you can run into error “Too many automatic redirections were attempted.”

Solving this issue can be little tricky.

How to enable automatic redirections using HTTPClient

Question is will you allow automatic redirections when you are doing HTTP requests?

If the answer is yes, you should set AllowAutoRedirect to true and specify how many automatic redirections you support using MaxAutomaticRedirections property. The default value is 50.

var handler = new HttpClientHandler() 
{
       AllowAutoRedirect = true,
       MaxAutomaticRedirections = 100
};
var client = new HttpClient(handler);

 

You are probably thinking that this code should work now but no.

Actually to support automatic redirection you also need to add CookieContainer to avoid getting caught in a redirect loop.

var handler = new HttpClientHandler() 
{
        AllowAutoRedirect = true,
        MaxAutomaticRedirections = 100,
        CookieContainer = new CookieContainer()
};
var client = new HttpClient(handler);

 

I hope this code will help someone solving similar issues.

If you want to learn more about ASP.NET Web API I recommend a great book that I love written by real experts:

BookWebAPIEvolvable

Designing Evolvable Web APIs with ASP.NET