c# - WebRequest - 防止重定向

标签 c# redirect httpwebrequest httpwebresponse http-status-code-302

我正在使用 WebRequest 读取 HTML 站点。服务器似乎正在重定向我的请求。

我的代码类似于以下内容:

    String URI = "http://www.foo.com/bar/index.html"
    WebRequest req = WebRequest.Create(URI);
    WebResponse resp = req.GetResponse();
    StreamReader sr = new StreamReader(resp.GetResponseStream());
    String returnedContent = sr.ReadToEnd();

当我检查 returnedContent 的内容时,它包含来自重定向的内容,例如“http://www.foo.com/FOO_BAR/index.html”。我确定我请求的 URL 存在,因为它是收到的响应的一部分(作为 IFrame)。

有没有办法阻止 WebResponse 被重定向并获取请求的 url 的内容?

更新

设置 req.AllowAutoRedirect = false 会导致 302 Found 状态代码,但不会传送实际内容。

更多细节: 我请求的 url 是 http://www.foo.com/bar/index.html 我收到的内容位于 http://www.foo.com/FOO_BAR/index。 html

响应看起来类似于:

<body>
    <div>
        <iframe src="/foo/index.html"></iframe>
    </div>
</body>

最佳答案

您可以使用HttpWebRequestAllowAutoRedirect property :

…
var req = (HttpWebRequest)WebRequest.Create(URI);
req.AllowAutoRedirect = false;
…

关于c# - WebRequest - 防止重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012384/

相关文章:

asp.net - 为 ASP.NET MVC 中的所有站外链接强制使用中间页面?

php - 如何对卡在重定向循环中的 CakePHP 应用程序进行故障排除?

javascript - 将多选引导下拉选项放在 div 之外(防止滚动冒泡)

c# - 创建具有 3 个条件的 Lambda 表达式

c# - 如何停靠选项卡控件

c# - gridview 中单个单元格的单击事件

css - 确定移动浏览器是否支持 CSS 和 javascript

C# - 同步 HttpWebRequest 以便从服务器获得响应

c# - 有人可以帮我做简单的算法吗?

.net - .NET HttpWebRequest 中的压缩( header )错误?