Getting the location from a WebClient on a HTTP 302 Redirect?

20,276

Solution 1

On HttpWebRequest you can set AllowAutoRedirect to false to handle the redirect yourself.

Solution 2

It's pretty easy to do

Let's assume you've created an HttpWebRequest called myRequest

// don't allow redirects, they are allowed by default so we're going to override
myRequest.AllowAutoRedirect = false;

// send the request
HttpWebResponse response = myRequest.GetResponse();

// check the header for a Location value
if( response.Headers["Location"] == null )
{
  // null means no redirect
}
else
{
  // anything non null means we got a redirect
}

Excuse any compile errors I don't have VS right in front of me, but I've used this in the past to check for redirects.

Solution 3

The HttpWebRequest has a property AllowAutoRedirect which you can set to false (it is always true for WebClient), and then get the Location HTTP header.

Share:
20,276
Michael Stum
Author by

Michael Stum

The same thing we do every night, Pinky. Try to take over the world! Full-Stack Developer on Stack Overflow Enterprise, working to make our little corner of the Internet better for all of us.

Updated on November 13, 2020

Comments

  • Michael Stum
    Michael Stum over 3 years

    I have a URL that returns a HTTP 302 redirect, and I would like to get the URL it redirects to.

    The problem is that System.Net.WebClient seems to actually follow it, which is bad. HttpWebRequest seems to do the same.

    Is there a way to make a simple HTTP Request and get back the target Location without the WebClient following it?

    I'm tempted to do raw socket communication as HTTP is simple enough, but the site uses HTTPS and I don't want to do the Handshaking.

    At the end, I don't care which class I use, I just don't want it to follow HTTP 302 Redirects :)