c# - 传递凭据适用于 WebRequest,但不适用于 HttpClient

标签 c# .net http dotnet-httpclient

我正在尝试使用 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));
            }

我不明白为什么一个有效而另一个无效。 对此的任何帮助或见解将不胜感激

最佳答案

如上所述herehere 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/

相关文章:

c# - Thread.Sleep 不工作!

.net - 如何在传输级别压缩来自 WCF .NET 的 HTTP 请求?

json - 仅针对聚合根更新 RESTful 资源

c# - 如何将秒转换为时分秒?

java - 不实际使用文件的 HTTP 文件上传

javascript - 即使使用看似有效的访问 token ,也无法通过 Postman 调用 Box API

c# - ASP.NET内存管理技术

c# - 创建委托(delegate) token - 无法创建 SecurityTokenService

c# - 使用 C# 使用 WebClient 对象 REST API 调用时出错

.net - 如何处理其他线程上的错误?