Using WebClient in C# is there a way to get the URL of a site after being redirected?

后端 未结 8 1503
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 03:21

Using the WebClient class I can get the title of a website easily enough:

WebClient x = new WebClient();    
string source = x.DownloadString(s);
string titl         


        
8条回答
  •  感情败类
    2020-11-29 03:53

    With an HttpWebRequest, you would set the AllowAutoRedirect property to false. When this happens, any response with a status code between 300-399 will not be automatically redirected.

    You can then get the new url from the response headers and then create a new HttpWebRequest instance to the new url.

    With the WebClient class, I doubt you can change it out-of-the-box so that it does not allow redirects. What you could do is derive a class from the WebClient class and then override the GetWebRequest and the GetWebResponse methods to alter the WebRequest/WebResponse instances that the base implementation returns; if it is an HttpWebRequest, then set the AllowAutoRedirect property to false. On the response, if the status code is in the range of 300-399, then issue a new request.

    However, I don't know that you can issue a new request from within the GetWebRequest/GetWebResponse methods, so it might be better to just have a loop that executes with HttpWebRequest/HttpWebResponse until all the redirects are followed.

提交回复
热议问题