c# - 即使 AllowAutoRedirect = true,HttpClient 也不会重定向

标签 c# .net .net-core dotnet-httpclient

我正在尝试解析维基空间页面,但无法获取实际页面。我不确定它是 HttpClient 错误还是某些缺少的配置。

这是我的代码:

HttpClientHandler handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
_httpClient = new HttpClient(handler);

HttpResponseMessage response = await _httpClient
    .GetAsync("http://medivia.wikispaces.com/Monsters");

当我运行该代码时,我得到 StatusCode 302 并被发送到 https://session.wikispaces.com/1/auth/auth?authToken=token .我希望 HttpClient 遵循 302,因为我有 AllowAutoRedirect = true

这是我第一次遇到这个问题。它适用于作为 RestSharp 一部分的 Postman 和 RestClient。

最佳答案

HttpClient 没有正确重定向的原因是该站点将您重定向到 HTTPS,然后再返回到 HTTP。一个快速的解决方法是改为 GET https://medivia.wikispaces.com/Monsters,无论如何这是一个更好的主意:

HttpResponseMessage response = await _httpClient.GetAsync("https://medivia.wikispaces.com/Monsters");
// Works fine! :)

我很好奇为什么第一种方法行不通,所以我进行了更深入的研究。如果您在浏览器或网络客户端中观察网络跟踪,就会发生以下情况:

GET http://medivia.wikispaces.com/Monsters
302 https://session.wikispaces.com/1/auth/auth?authToken=token
302 http://medivia.wikispaces.com/Monsters?redirectToken=token

从加密 (HTTPS) 连接到未加密连接的 302 导致 HttpClientHandler 停止自动跟随。据我所知,这是 Windows implementation of HttpClientHandler 的安全怪癖。 ,因为 Unix one在我的非正式测试中似乎并不关心 HTTPS->HTTP 重定向。

关于c# - 即使 AllowAutoRedirect = true,HttpClient 也不会重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42405183/

相关文章:

.net - 隐藏在Visual Studio中的项目文件

azure - 将应用程序功能服务总线触发器切换为 ReceiveAndDelete 模式而不是 PeekLock

c# - 如何以正确的方式将 nuget 包添加到 package.config?

c# - 我如何并行化这种模式?

c# - .NET Core 中的 Nuget 依赖项

c# - 是否有可能完全用托管 .NET 语言编写 JIT 编译器(针对 native 代码)

c# - Entity Framework 核心: many-to-many relationship with the same object

c# - FluentScheduler 构造函数中的依赖注入(inject)

c# - 生成随机 boolean 概率

c# - Enumerable.Empty<T>() 是代替 foreach 循环中的 null 检查的好选择(C#)?