问题
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