HttpClient Follow 302 Redirects in .NET Core
By FoxLearn 1/10/2025 7:36:57 AM 31
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
).
- How to Convert string to JSON in C#
- How to take a screenshot with Selenium WebDriver
- Sending JSON in .NET Core
- Writing Files Asynchronously with Multiple Threads in .NET Core
- Manipulating XML Google Merchant Data with C# and LINQ
- Set Local Folder for .NET Core in C#
- How to Remove Duplicates from a List with LINQ in C#
- Ignoring Namespaces in XML when Deserializing in C#