C # HttpWebRequest - how to determine if HTTP 301 has occurred?

I am testing my HTTP 301 redirects (constantly moving) for an ASP.NET MVC web application.

I 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 that the status code is HTTP 200 (OK), because it reads the last response (like a redirected page).

The url will get into my redirect controller, which returns this:

 return RedirectToRoutePermanent("SomeRoute", new { id = someId }); 

And this is what I want to capture, not the 200 page that it is being redirected to.

How can I do it?

+7
source share
2 answers

You need to disable automatic redirection:

 req.AllowAutoRedirect = false; 
+12
source

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

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

You can also set the maximum number of MaximumAutomaticRedirections that follows the MaximumAutomaticRedirections property.

use this to stop the automatic redirection myHttpWebRequest.AllowAutoRedirect=false;

+1
source

All Articles