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

后端 未结 4 1985
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 17:08

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,

相关标签:
4条回答
  • 2020-12-03 17:21

    Also, for someone who just needs the new location, HttpResponseMessage has a RequestMessage property. Sometimes it can be useful, because WebClient doesn't support changing the AllowAutoRedirect property once it's been set.

    0 讨论(0)
  • 2020-12-03 17:22

    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.

    0 讨论(0)
  • 2020-12-03 17:30

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

    0 讨论(0)
  • 2020-12-03 17:33

    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.

    0 讨论(0)
提交回复
热议问题