即使AllowAutoRedirect

即使AllowAutoRedirect

本文介绍了即使AllowAutoRedirect = true,HttpClient也不会重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析Wikispaces页面,但无法获得实际页面.我不确定是否是HttpClient错误或缺少某些配置.

I'm trying to parse a wikispaces page but I'm not able to get the actual page. I'm not sure if its a HttpClient bug or some missing configuration.

这是我的代码:

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 .

When i run that code I get the StatusCode 302 and get sent to https://session.wikispaces.com/1/auth/auth?authToken=token. I expect the HttpClient to follow a 302 because I have AllowAutoRedirect = true.

这是我第一次遇到此问题.它可以与PostSharp和RestSharp的RestClient一起很好地工作.

This is the first time I've encountered this problem. It works fine with Postman and RestClient which is part of RestSharp.

推荐答案

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自动停止跟踪.据我所知,这是 Windows实现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.

这篇关于即使AllowAutoRedirect = true,HttpClient也不会重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:25