开发者

C# HttpWebRequest - How to determine if HTTP 301 Occured?

I'm doing some testing of my HTTP 301 redirects (moved permanently) for an ASP.NET MVC web application.

I've created a test page with the following code:

try
{
    var req = (HttpWebRequest) WebRequest.Create(url);
    resp = (HttpWebResponse) req.GetResponse();
    return Json(new {statusCode = (int) resp.StatusCode});  
}
catch (Exception exc)
{
    return Json(new { statusCode = (int)HttpStatusCode.InternalServerError });
}
finally
{
    if (resp != null) resp.Close();
}

But the problem is, the status code is HTTP 200 (OK), because it's reading the last response (e.g the page it got redirected to).

The URL will hit my redirect controller, which returns this:

return RedirectToRouteP开发者_如何学运维ermanent("SomeRoute", new { id = someId });

And that's what i want to capture, not the 200 of the page it gets redirected to.

How do i do it?


You'll need to turn off automatic redirection following:

req.AllowAutoRedirect = false;


Set AllowAutoRedirect to true if you want the request to automatically follow HTTP redirection headers to the new location of the resource.

If AllowAutoRedirect is set to false, all responses with an HTTP status code from 300 to 399 is returned to the application.

you can also set The maximum number of redirections to follow by the MaximumAutomaticRedirections property.

use this to stop auto redirection myHttpWebRequest.AllowAutoRedirect=false;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜