我正在尝试使用 HttpClient 将凭据传回 Web 服务。 但是,我不断收到未经授权的请求。 但是,当我尝试使用 WebRequest 时它会进行身份验证吗?
HttpClient:
var handler = new NativeMessageHandler
{
UseDefaultCredentials = true,
Credentials = credential
};
var client = new HttpClient(handler);
var content = _httpClientHelper.Serialize(data);
var response = await _client.PostAsync($"{_baseurl}/api/foos/List", content);
网络请求:
HttpResponseMessage response = null;
try
{
var data = JsonConvert.SerializeObject(new
{
ViewTitle = "New",
PageCount = 60
});
var content = _httpClientHelper.Serialize(data);
using (var client = new WebClient { UseDefaultCredentials = true, Credentials = credentials })
{
client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
client.UploadData("$"{baseurl}/api/foos/List", "POST", Encoding.UTF8.GetBytes(content));
}
我不明白为什么一个有效而另一个无效。 对此的任何帮助或见解将不胜感激
最佳答案
如上所述here和 here HttpClient 的这种行为可能是由于 HttpClientHandler 的实现方式造成的。
"[..] the StartRequest method is executed in new thread with the credentials of the asp.net process (not the credentials of the impersonated user) [..]"
您可能会看到 HttpClient 和 WebClient 的行为差异,因为
"HttpClient creates new threads via the Task Factory. WebClient on the other hand, runs synchronously on the same thread thereby forwarding its credentials (i.e. the credentials of the impersonated user) ."
关于c# - 传递凭据适用于 WebRequest,但不适用于 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49881955/