【发布时间】:2013-10-29 18:26:25
【问题描述】:
我的代码正在对需要基本身份验证的 Web 服务 URL 进行 HTTP GET。
我使用 HttpClient 和定义了 Credentials 属性的 HttpClientHandler 实现了这一点。
这一切都很完美。除了我将经过身份验证的 GET 的用例之一:
http://somedomain.com 重定向到 http://www.somedomain.com。
似乎 HttpClientHandler 在重定向期间清除了身份验证标头。我怎样才能防止这种情况?无论重定向如何,我都希望发送凭据。
这是我的代码:
// prepare the request
var request = new HttpRequestMessage(method, url);
using (var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password) , PreAuthenticate = true })
using (var client = new HttpClient(handler))
{
// send the request
var response = await client.SendAsync(request);
注意:这是一个相关的问题: Keeping HTTP Basic Authentification alive while being redirected 但由于我使用不同的类来发出请求,可能会有更好、更具体的解决方案
【问题讨论】:
-
旁注,我认为在这种情况下设计的行为没有意义。我将凭据设置为客户端的一部分,而不是根据特定的 URI(请求)。由于同一个客户端可以执行多个请求,并且无论它们的 URI 是什么都会发送授权,这很愚蠢
标签: c# .net authentication redirect dotnet-httpclient