C# HttpWebRequest - 如何确定是否发生 HTTP 301?

发布于 2024-11-28 02:56:35 字数 679 浏览 4 评论 0原文

我正在对 ASP.NET MVC Web 应用程序的 HTTP 301 重定向(永久移动)进行一些测试。

我使用以下代码创建了一个测试页面:

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();
}

但问题是,状态代码是 HTTP 200(正常),因为它正在读取最后一个响应(例如,它重定向到的页面)。

URL 将到达我的重定向控制器,该控制器返回以下内容:

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

这就是我想要捕获的内容,而不是它重定向到的页面的 200。

我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等数载,海棠开 2024-12-05 02:56:35

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

req.AllowAutoRedirect = false;

You'll need to turn off automatic redirection following:

req.AllowAutoRedirect = false;
一紙繁鸢 2024-12-05 02:56:35

如果您希望请求自动遵循 HTTP 重定向标头到达资源的新位置,请将 AllowAutoRedirect 设置为 true。

如果 AllowAutoRedirect 设置为 false,则所有 HTTP 状态代码从 300 到 399 的响应都会返回到应用程序。

您还可以通过 MaximumAutomaticRedirections 属性设置要遵循的最大重定向次数。

用它来停止自动重定向
myHttpWebRequest.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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文