HttpClient身份validation标头未被发送

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

 HttpRequestMessage request = new HttpRequestMessage( 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(); }).Unwrap().Result; 

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

我已经看过了 ,但我认为我已经将身份validation方案指定为AuthenticationHeaderValue构造函数的一部分。

有没有我错过的东西?

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

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

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

 HttpRequestMessage request = new HttpRequestMessage( 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(); }) .Unwrap().Result; 

尝试在客户端上设置标题:

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

这对我有用。

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

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

实际上你的问题是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);