【发布时间】:2015-02-17 15:28:00
【问题描述】:
以下是执行身份验证、生成授权标头和调用 API 的代码。
不幸的是,在 API 上的 GET 请求之后,我收到了 401 Unauthorized 错误。
但是,当我在 Fiddler 中捕获流量并重放时,API 调用成功,我可以看到所需的200 OK 状态码。
[Test]
public void RedirectTest()
{
HttpResponseMessage response;
var client = new HttpClient();
using (var authString = new StringContent(@"{username: ""theUser"", password: ""password""}", Encoding.UTF8, "application/json"))
{
response = client.PostAsync("http://host/api/authenticate", authString).Result;
}
string result = response.Content.ReadAsStringAsync().Result;
var authorization = JsonConvert.DeserializeObject<CustomAutorization>(result);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authorization.Scheme, authorization.Token);
client.DefaultRequestHeaders.Add("Accept", "application/vnd.host+json;version=1");
response =
client.GetAsync("http://host/api/getSomething").Result;
Assert.True(response.StatusCode == HttpStatusCode.OK);
}
当我运行此代码时,授权标头会丢失。
但是,在 Fiddler 中,该标头已成功传递。
知道我做错了什么吗?
【问题讨论】:
-
什么时候发生重定向?您使用哪个 HTTP 代码进行重定向?
-
@tia 我得到 307 临时重定向
-
@pixelbadger 它看起来像同样的问题。我很失望没有解决方案。目前我正在做的正是问这个问题的人。在我的应用程序中,我直接使用 https 来绕过重定向。
标签: c# .net rest dotnet-httpclient