简体   繁体   中英

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

您需要关闭以下自动重定向

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM