且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-21 19:02:58

HttpClient不能正确重定向的原因是因为站点将您重定向到HTTPS,然后又重定向到HTTP.快速解决方案是改为获取 https://medivia.wikispaces.com/Monsters ,无论如何,这是一个更好的主意:

The reason the HttpClient isn't redirecting properly is because the site is redirecting you to HTTPS and then back to HTTP. A quick fix is to GET https://medivia.wikispaces.com/Monsters instead, which is a better idea anyhow:

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

我很好奇为什么它不能一开始就起作用,所以我更深入地研究了.如果您在浏览器或网络客户端中观看网络跟踪,则会发生以下情况:

I was curious why it didn't work the first way, so I dug a little deeper. If you watch the network trace in a browser or a network client, this is what happens:

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自动停止跟踪.据我所知,这是 Unix 在我的非正式测试中似乎并不关心HTTPS-> HTTP重定向.

That 302 from an encrypted (HTTPS) connection to an unencrypted one is causing the HttpClientHandler to stop automatically following. From what I can tell, this is a security quirk of the Windows implementation of HttpClientHandler, because the Unix one didn't seem to care about the HTTPS->HTTP redirect in my informal testing.