8

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 RedirectToRoutePermanent("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?

RPM1984
  • 72,246
  • 58
  • 225
  • 350

2 Answers2

14

You'll need to turn off automatic redirection following:

req.AllowAutoRedirect = false;
porges
  • 30,133
  • 4
  • 83
  • 114
1

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;