简体   繁体   English

C#HttpWebRequest - 如何确定HTTP 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. 我正在为ASP.NET MVC Web应用程序测试我的HTTP 301重定向(永久移动)。

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). 但问题是,状态代码是HTTP 200(OK),因为它正在读取最后一个响应(例如它被重定向到的页面)。

The URL will hit my redirect controller, which returns this: 该URL将命中我的重定向控制器,它返回:

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

And that's what i want to capture, not the 200 of the page it gets redirected to. 这就是我想要捕获的内容,而不是它被重定向到的200页面。

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. 如果希望请求自动将HTTP重定向标头跟随到资源的新位置,请将AllowAutoRedirect设置为true。

If AllowAutoRedirect is set to false, all responses with an HTTP status code from 300 to 399 is returned to the application. 如果AllowAutoRedirect设置为false,则将HTTP状态代码为300到399的所有响应返回给应用程序。

you can also set The maximum number of redirections to follow by the MaximumAutomaticRedirections property. 您还可以设置MaximumAutomaticRedirections属性要遵循的最大重定向数。

use this to stop auto redirection myHttpWebRequest.AllowAutoRedirect=false; 使用它来停止自动重定向myHttpWebRequest.AllowAutoRedirect=false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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