【问题标题】:HttpClient doesn't retrieve header "Location" in response (while the browser request does)HttpClient 不会在响应中检索标头“Location”(而浏览器请求会)
【发布时间】:2019-09-09 20:28:09
【问题描述】:

我正在浏览器中执行调用,然后检查内容。 Chrome 告诉我响应标头包含一个名为 Location 的标头。当我使用HttpClient 执行对同一URL 的调用时,我也得到了标题,但它是null。我没有信心判断是我遗漏了什么,还是HttpClient instance 的操作方式与浏览器的操作方式不同。

首先,我正在获取允许我在目标页面识别自己的 cookie。

string url = "https://www.pensionsmyndigheten.se/service/login/login"
  + "?targetPage=https://www.pensionsmyndigheten.se/service/overview/"
  + "&failurePage=https://www.pensionsmyndigheten.se/service/login/error/login-failed"
  + "&cancelPage=https://www.pensionsmyndigheten.se/";
Uri uri = new Uri(url);
CookieContainer cookieJar = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler { CookieContainer = cookieJar };
HttpClient client = new HttpClient(handler);

HttpResponseMessage result = client.GetAsync(uri).Result;
Cookie cookie = cookieJar.GetCookies(uri).First(e => e.Name == "pm_retention_urls");

然后,我尝试使用此 cookie 获取允许我发送授权请求的 SAML 查询字符串。

string url = "https://www.pensionsmyndigheten.se/service/login/discoresponse"
  + "?spId=default"
  + "&entityID=https%3A%2F%2Feid.legitimeringstjanst.se%2Fmobilt-bankid%2F";
Uri uri = new Uri(url);
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(cookie);
HttpClientHandler handler = new HttpClientHandler { CookieContainer = cookieJar };
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Referrer = uri;

HttpResponseMessage response = client.GetAsync(uri).Result;
HttpResponseHeaders headers = response.Headers;

我不确定下一步如何解决它。谷歌搜索确认这是一般情况下的正确方法。显然,与在浏览器中进行的操作相比,我正在做一些不同的事情,但我不能说如何推断出什么,更不用说如何解决它了。

【问题讨论】:

标签: c# http-headers httpclient saml


【解决方案1】:

http 客户端使用的处理程序默认自动重定向,并从结果中删除重定向响应标头。或者您可以说它不会将标头转发到最终响应。 如果禁用自动重定向,则可以读取响应中的位置标头。您应该注意自己调用重定向目标,直到获得实际结果。

var handler = new HttpClientHandler
{
    CookieContainer = cookieJar,
    AllowAutoRedirect = false
};
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Referrer = uri;
var response = client.GetAsync(uri).Result;
var location = response.Headers["Location"];
// Call the get operation on the location url to continue.

还有 - 更多 useful reading.

【讨论】:

  • 您的回答解决了我的问题 - 这是 AllowAutoRedirect 上的 false。不过,我有后续行动。就我而言,我必须使用 response.Headers.Location 因为您建议的语法 response.Headers["Location"] 无法编译。您使用的是哪个版本的 .NET?
  • 哦,还有一件事。你让我走了,但我注意到另一个问题。我在another question问过,有时间可以看一下。提前致谢。
  • @KonradViltersten 我可能一直在使用 .Net 框架,因为从标签中并不清楚。不过这并不重要。使用.Location 获取位置基本相同。
猜你喜欢
  • 1970-01-01
  • 2018-11-16
  • 2011-08-18
  • 2014-06-17
  • 2018-06-04
  • 2015-12-05
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多