C# HttpClient 和 Windows 身份验证:无法访问关闭的流

Kin*_*101 6 .net c# .net-4.7.1

我正在使用带有处理程序的本机 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
            {

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Kin*_*101 1

经过一些新的调查后,我认为/担心HttpClientHandler (或 HttpClient)中存在Microsoft 错误:

如果我不使用 PostAsync 方法,而是使用 SendAsync 方法,我可以使用更多选项来编写请求,尤其是将HTTP 版本1.1(默认情况下)更改为1.0。然后在这种情况下,真正的异常被揭示(并且它不再被 ObjectDisposeException 异常隐藏/覆盖)。供您参考,我真正的例外情况如下:

--> 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)
            {

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意:降级 HTTP 版本只是为了获取真正的异常消息,HTTP 1.0 已经很老了。

任何专家分析将不胜感激。希望这会帮助其他人。