Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net-core

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?

like image 905
Martin Heralecký Avatar asked Nov 17 '25 06:11

Martin Heralecký


1 Answers

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
like image 106
Hieu Avatar answered Nov 19 '25 22:11

Hieu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!