HttpClient身份验证标头未被发送

时间:2012-04-09 17:38:57

标签: c# .net-4.5 wcf-web-api dotnet-httpclient

我正在尝试将HttpClient用于需要基本HTTP身份验证的第三方服务。我正在使用AuthenticationHeaderValue。这是我到目前为止所提出的:

HttpRequestMessage<RequestType> request = 
    new HttpRequestMessage<RequestType>(
        new RequestType("third-party-vendor-action"),
        MediaTypeHeaderValue.Parse("application/xml"));
request.Headers.Authorization = new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
        string.Format("{0}:{1}", "username", "password"))));

var task = client.PostAsync(Uri, request.Content);
ResponseType response = task.ContinueWith(
    t =>
    {
        return t.Result.Content.ReadAsAsync<ResponseType>();
    }).Unwrap().Result;

看起来POST操作正常,但我没有收到我期望的数据。通过一些反复试验,并最终使用Fiddler来嗅探原始流量,我发现授权标头没有被发送。

我见过this,但我认为我已经将身份验证方案指定为AuthenticationHeaderValue构造函数的一部分。

有没有我错过的东西?

4 个答案:

答案 0 :(得分:29)

您的代码看起来应该可以正常工作 - 我记得遇到类似的问题设置授权标头并通过执行Headers.Add()而不是设置它来解决:

request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", "password"))));

<强>更新 看起来像是在执行request.Content时,并非所有标头都反映在内容对象中。你可以通过检查request.Headers和request.Content.Headers来看到这一点。您可能想要尝试的一件事是使用SendAsync而不是PostAsync。例如:

HttpRequestMessage<RequestType> request = 
     new HttpRequestMessage<RequestType>(
         new RequestType("third-party-vendor-action"),
         MediaTypeHeaderValue.Parse("application/xml"));

request.Headers.Authorization = 
    new AuthenticationHeaderValue(
        "Basic", 
        Convert.ToBase64String(
            System.Text.ASCIIEncoding.ASCII.GetBytes(
                string.Format("{0}:{1}", "username", "password"))));

 request.Method = HttpMethod.Post;
 request.RequestUri = Uri;
 var task = client.SendAsync(request);

 ResponseType response = task.ContinueWith(
     t => 
         { return t.Result.Content.ReadAsAsync<ResponseType>(); })
         .Unwrap().Result;

答案 1 :(得分:18)

这也可以,你不必处理base64字符串转换:

var handler = new HttpClientHandler();
handler.Credentials = new System.Net.NetworkCredential("username", "password");
var client = new HttpClient(handler);
...

答案 2 :(得分:17)

尝试在客户端设置标题:

DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", userName, password))));

这适合我。

答案 3 :(得分:4)

实际上您的问题出在PostAsync - 您应该使用SendAsync。在您的代码中 - client.PostAsync(Uri, request.Content);仅发送不包含请求邮件标头的内容。 正确的方法是:

HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, url)
{
    Content = content
};
message.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);
httpClient.SendAsync(message);