Handling Redirects with HttpClient in C#

By FoxLearn 1/21/2025 9:13:21 AM   29
By default, HttpClient handles redirects automatically. When a request results in a 3xx response code (e.g., 301, 302), HttpClient follows the Location header and makes a new request to the provided URL.

You can disable this automatic redirection by configuring an HttpClientHandler with the AllowAutoRedirect property set to false. This will allow you to capture the redirect response and handle it manually if desired.

var handler = new HttpClientHandler()
{
   AllowAutoRedirect = false // Disable automatic redirects
};
var client = new HttpClient(handler);

var response = await client.GetAsync("http://example.com/redirect");

Console.WriteLine($"Status Code: {(int)response.StatusCode}");
Console.WriteLine($"Redirect URL: {response.Headers.Location}");

Output:

Status Code: 301
Redirect URL: https://example.com/new-location

In this case, you can manually handle the redirect based on the Location header.

Default Redirect Behavior

HttpClient uses an internal RedirectHandler to follow redirects. The conditions for a redirect include:

  • A 3xx status code (e.g., 301, 302, 307, etc.)
  • A valid Location header with a URI to redirect to.
  • A maximum of 50 redirects (this is configurable).

Handling Redirects Manually

When you disable auto-redirects, you can manually examine the Location header and decide how to handle the redirect.

Here’s an example where you manually combine the query parameters from the original request with the new URL:

var originalUri = new Uri("http://example.com/redirect?query=example");
var redirectUri = new Uri(response.Headers.Location, UriKind.RelativeOrAbsolute);

// Combine original query string with the redirect URI
var finalUri = new UriBuilder(redirectUri) { Query = originalUri.Query }.Uri;

var finalResponse = await client.GetAsync(finalUri);

Forced GET Requests

In certain cases, such as a 302 redirect after a POST request, HttpClient may automatically convert the HTTP method to GET.

This can cause issues if the redirect location does not support the GET method.

System.Net.Http.HttpRequestException: Response status code does not indicate success: 405 (Method Not Allowed).

To avoid unexpected behavior, you can handle the redirect manually by checking the status code and request method.

Checking if the Request Was Redirected

One simple way to detect a redirect is by comparing the original request URI with the response URI:

var originalUri = new Uri("http://example.com/redirect");
var response = await client.GetAsync(originalUri);

if (originalUri != response.RequestMessage.RequestUri)
{
    Console.WriteLine($"Request was redirected to {response.RequestMessage.RequestUri}");
}

Output:

Request was redirected to https://example.com/new-location

Limiting Redirects

You can control the maximum number of redirects by setting the MaxAutomaticRedirections property on the HttpClientHandler:

var handler = new HttpClientHandler()
{
   MaxAutomaticRedirections = 3 // Limit redirects to 3
};

var client = new HttpClient(handler);
var response = await client.GetAsync("http://example.com/redirect");

If the number of redirects exceeds this limit, HttpClient will throw an exception.