Martin Heralecký
Martin Heralecký

Reputation: 5779

How to force HttpClient to follow HTTPS -> HTTP redirect?

I need to perform an HTTP GET operation while following redirects.

using (var client = new HttpClient())
{
    var response = await client.GetAsync("https://example.com");
}

Problem is that if the server returns a 302 HTTP code redirecting to http://... (not https), .NET does not follow it (for security reasons).

How do I force HttpClient to follow redirects from HTTPS to HTTP?

Upvotes: 3

Views: 1888

Answers (1)

Hieu
Hieu

Reputation: 7674

You may have to do a little bit of extra work:

    using var client = new HttpClient();
    var response = await client.GetAsync("https://example.com");
    if (new[] {HttpStatusCode.Moved, HttpStatusCode.MovedPermanently}.Contains(response.StatusCode))
    {
        response = await client.GetAsync(response.Headers.Location);
    }
    // more code

Upvotes: 1

Related Questions