HttpClient Follow 302 Redirects in .NET Core

By FoxLearn 1/10/2025 7:36:57 AM   31
In .NET Core, the HttpClient class does not automatically follow HTTP redirects, including 302 (Found) and 301 (Moved Permanently) responses.

To enable this behavior, you need to configure the HttpClientHandler to allow automatic redirections.

Configure HttpClient to Follow Redirects

You can create an HttpClient with a custom HttpClientHandler where the AllowAutoRedirect property is set to true. Additionally, you can limit the number of redirects with the MaxAutomaticRedirections property.

private static HttpClient _httpClient = new HttpClient(
    new HttpClientHandler 
    { 
        AllowAutoRedirect = true, 
        MaxAutomaticRedirections = 5  // Set the max number of allowed redirects
    }
);

In the example above, the HttpClient will automatically follow up to 5 redirects. Keep in mind that redirects from HTTPS to HTTP are not allowed for security reasons.

Make Requests with Redirects

Once your HttpClient is set up, you can use it to send requests that may involve redirects. For example, let's say you need to fetch an RSS feed, and the URL you're accessing returns a 301 redirect to another URL:

public static async Task<string> GetRss()
{
    // The URL "/rss" might return a 301 redirect, but the code will follow
    // the redirect and get the content from the final destination
    var response = await _httpClient.GetAsync("https://foxlearn.com/rss");

    if (!response.IsSuccessStatusCode)
        throw new Exception($"The requested feed returned an error: {response.StatusCode}");

    var content = await response.Content.ReadAsStringAsync();
    return content;
}

In this case, the initial request to https://foxlearn.com/rss will result in a 301 redirect, but because AllowAutoRedirect is set to true, the HttpClient will follow the redirect automatically and retrieve the content from the final URL.

By configuring HttpClient to allow automatic redirections, you ensure that it can seamlessly follow HTTP redirects, such as 302 or 301 responses. Just be sure to set AllowAutoRedirect to true and specify how many redirects you are willing to follow (using MaxAutomaticRedirections).