【发布时间】:2019-01-07 19:43:01
【问题描述】:
我正在尝试检索 TLS 版本信息。我下面的代码使用 HttpClient 成功进行了 HTTP GET 调用。我错过了什么?从哪里获取 HttpClient 的 TLS 版本信息?
我正在做与Which TLS version was negotiated? 中建议的相同的事情,但这是特定于 WebRequest 的,它与 HttpClient 不同。
static async Task MainAsync()
{
Uri baseURI = new Uri("https://jsonplaceholder.typicode.com/posts/1");
string apiPath = "";
using (var client = new HttpClient())
{
client.BaseAddress = baseURI;
HttpResponseMessage response = await client.GetAsync(apiPath);
Console.WriteLine("HTTP status code: " + response.StatusCode.ToString());
GetSSLConnectionInfo(response, client.BaseAddress.ToString(), apiPath);
}
Console.ReadKey();
}
static async Task GetSSLConnectionInfo(HttpResponseMessage response, string baseURI, string apiPath)
{
using (Stream stream = await response.RequestMessage.Content.ReadAsStreamAsync())
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
Stream CompressedStream = null;
if (stream.GetType().BaseType == typeof(GZipStream))
{
CompressedStream = (GZipStream)stream;
}
else if (stream.GetType().BaseType == typeof(DeflateStream))
{
CompressedStream = (DeflateStream)stream;
}
var objbaseStream = CompressedStream?.GetType().GetProperty("BaseStream").GetValue(stream);
if (objbaseStream == null)
{
objbaseStream = stream;
}
var objConnection = objbaseStream.GetType().GetField("m_Connection", bindingFlags).GetValue(objbaseStream);
var objTlsStream = objConnection.GetType().GetProperty("NetworkStream", bindingFlags).GetValue(objConnection);
var objSslState = objTlsStream.GetType().GetField("m_Worker", bindingFlags).GetValue(objTlsStream);
SslProtocols b = (SslProtocols)objSslState.GetType().GetProperty("SslProtocol", bindingFlags).GetValue(objSslState);
Console.WriteLine("SSL Protocol Used for " + baseURI + apiPath + System.Environment.NewLine + "The TLS version used is " + b);
}
}
我期待 TLS 连接信息,但出现异常。
【问题讨论】:
-
我的团队试图做同样的事情,但基本上得出的结论是,这是不可能的。
-
你遇到了什么异常?
-
永远不要使用
async void -
@abatishchev 抱歉,它只是测试代码。我得到的异常是 System.NullReferenceException: 'Object reference not set to an instance of an object。当他们开始阅读 objbaseStream 时就会发生这种情况。
-
您的实现依赖于反射,反射本质上和可以理解的片状。调试并找出导致 NullReferenceException 的行意味着您要查找的内容不存在/命名不同。