我正在使用带有处理程序的 native C#HTTP客户端来处理Windows身份验证,并且我使用ObjectDisposedException
。
using (var httpClientHandler = new HttpClientHandler { Credentials = CredentialCache.DefaultNetworkCredentials })
{
bool disposeHandler = true; //Setting true or false does not fix the problem
using (var httpClient = new HttpClient(httpClientHandler, disposeHandler))
{
using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes("Hello")))
{
// Commenting/uncommenting the line below does not fix the problem
// httpRequestMessage.Headers.Connection.Add("Keep-Alive");
using (var httpResponseMessage = await httpClient.PostAsync("http://SomeUrl", content)) // This line throws an ObjectDisposedException
{
}
}
}
}
任何想法?
最佳答案
经过一些新的调查,我认为/担心在HttpClientHandler(或HttpClient)中存在一个 Microsoft错误:
如果我不是使用PostAsync方法而是使用SendAsync方法,则可以为我的请求添加更多选项,尤其是将 HTTP版本从 1.1 (默认)更改为 1.0 。然后在这种情况下,真正的异常就被揭示了(它不再被ObjectDisposedException异常隐藏/覆盖)。供您引用,我真正的异常(exception)是:
-> System.Net.WebException:远程服务器返回错误:(401)未经授权。
-> System.ComponentModel.Win32Exception:目标主体名称不正确
(仅供引用,此异常是由于Active Directory中用户的SPN配置错误所致)using (var httpClientHandler = new HttpClientHandler { Credentials = CredentialCache.DefaultNetworkCredentials })
{
bool disposeHandler = true; //Setting true or false does not fix the problem
using (var httpClient = new HttpClient(httpClientHandler, disposeHandler))
{
using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes("Hello")))
{
// Commenting/uncommenting the line below does not fix the problem
// httpRequestMessage.Headers.Connection.Add("Keep-Alive");
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://SomeUrl")
{
Content = content,
Version = HttpVersion.Version10
};
using (var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage)) // This line still throws but with the real exception (and not the ObjectDisposedException)
{
}
}
}
}
当心:降级HTTP版本只是获得真正异常消息的一种手段,HTTP 1.0变得很老。
任何专家的分析将不胜感激。希望这对其他人有帮助。
关于C#HttpClient和Windows身份验证: Cannot access a closed Stream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55611139/