Search code examples
c#asp.netasp.net-mvchttpwebrequesthttp-status-code-301

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 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?


Solution

  • You'll need to turn off automatic redirection following:

    req.AllowAutoRedirect = false;