How can I detect if a URL is redirected to another one?

这一生的挚爱 提交于 2019-12-24 03:19:33

问题


I use this code to make a 'GET' request to urls.

var request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";
var response = request.GetResponse() as HttpWebResponse;
var status = response.StatusCode; // returns HttpStatusCode.OK

So, the probelem is when a url is redirected to another one, I can't detect it. For example;

url is: http://site.com

that redirects to http://www.site.com

but when I make a request to http://site.com it returns a HttpStatusCode.OK for it -instead of a redirect code. Have you any idea please?


回答1:


You can use the AllowAutoRedirect property. Set it to false and handle the redirect yourself.




回答2:


Use the HttpWebRequest.Address property, which is explicitly defined as "the URI after any redirections that happen during the request are complete"

Note that this should be used instead of the similar HttpWebResponse.ResponseUri, as its documentation says:

Applications that need to access the last redirected ResponseUri should use the HttpWebRequest..::..Address property rather than ResponseUri, since the use of ResponseUri property may open security vulnerabilities.



来源:https://stackoverflow.com/questions/11618704/how-can-i-detect-if-a-url-is-redirected-to-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!