繁体   English   中英

如何获得 HttpClient POST 请求中使用的协商 TLS 版本

[英]How can I get negotiated TLS version used in HttpClient POST requests

我正在尝试获取 HttpClient SendAsync 调用中使用的 TLS 版本信息。 我已经尝试了此链接中的方法Detecting TLS Version used for HttpClient POST or GET calls但是当我在调试模式下运行它时,我发现 object 处理的异常在获取 SslProtocol 属性时出现。 有什么方法可以阻止 .net 处理 object 属性,直到我阅读它们。

这是代码:

public bool ExecuteAsync()
{
    using (var client = new HttpClient())
    {
        using (var response = client.GetAsync("https://example.com/").Result)
        {
            if (response.Content is StreamContent)
            {
                var webExceptionWrapperStream = GetPrivateField(response.Content, "content");
                var connectStream = GetBasePrivateField(webExceptionWrapperStream, "innerStream");
                var connection = GetPrivateProperty(connectStream, "Connection");
                var tlsStream = GetPrivateProperty(connection, "NetworkStream");
                var state = GetPrivateField(tlsStream, "m_Worker");
                var protocol = (SslProtocols)GetPrivateProperty(state, "SslProtocol");
                Console.WriteLine(protocol);
            }
            else
            {
                // not sure if this is possible
            }
        }
    }
return true;
}

private static object GetPrivateProperty(object obj, string property)
{
    return obj.GetType().GetProperty(property, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
}

private static object GetPrivateField(object obj, string field)
{
    return obj.GetType().GetField(field, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
}

private static object GetBasePrivateField(object obj, string field)
{
    return obj.GetType().BaseType.GetField(field, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
}

另外,我已经在其他代码中运行了上述链接中的解决方案并且它正在运行。 我发现的不同之处在于,当我在主线程中完成所有工作时,其他代码正在启动新线程以进行 SendAsync 调用。 另外,我在某处读到,对上面链接中使用的 SendAsync 方法使用“使用”语句不是一个好习惯。

此外,是否有任何其他方法可以获取 TLS 版本信息。 我听说可以从 .net 框架日志中读取它,但我不知道该怎么做。

如果我能获得与 TLS stream 相关的其他信息,例如 hash 算法和密码算法,那就太好了。 另外,我使用的是.net framework 4.6.1 会对问题有影响吗?

我找到了一种在代码中读取 System.Net 跟踪的方法,借助此处给出的代码System.Net (HttpWebRequest) tracking without using files or app.config? 通过@MarkoW。

我得打电话

ExecuteWithEnabledSystemNetLogging(SourceLevels webTraceSourceLevel, Action actionToExecute, params TraceListener[] listener).

就我而言,输入变量如下。

webTraceSourceLevel 是SourceLevels.Information

actionToExecute 是我的方法,它发送我需要 system.net 跟踪的 HttpClient 请求,分配给 Action object。

侦听器是TextWriterTraceListener myTextListener = new TextWriterTraceListener(stream)

// 其中 stream 是 stream object ,其中我的 system.net 跟踪与我传递的操作相关,后来我将其转换为字符串。

有了这个,我得到了 tls 版本和其他密码相关信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM