C# System.Net.ServicePointManager.SecurityProtocol正在使用中

C# System.Net.ServicePointManager.SecurityProtocol正在使用中,c#,https,httpclient,servicepointmanager,C#,Https,Httpclient,Servicepointmanager,我们有一个C#类,服务器和web应用程序都使用该类从第三方web服务获取信息。目前,该服务可通过http和https访问。我们正试图让类使用https,因为我们相信第三方将来只允许https访问 这是我们的代码: using (HttpClient httpClient = new HttpClient()) { try { //specify to use TLS 1.2 as default co

我们有一个C#类,服务器和web应用程序都使用该类从第三方web服务获取信息。目前,该服务可通过http和https访问。我们正试图让类使用https,因为我们相信第三方将来只允许https访问

这是我们的代码:

using (HttpClient httpClient = new HttpClient())
        {
            try
            {
                //specify to use TLS 1.2 as default connection
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                var uri = new Uri(url);
                string uriStr = uri.ToString();
                string msg = $"uri: {uriStr}";

                ApplicationLogger.Singleton.LogMessage(LogCategories.General, System.Diagnostics.TraceEventType.Verbose, msg, "GetUrlResponseString - uri");

                var task =  httpClient.GetStringAsync(uri);
                task.Wait();

                string taskBools = "";
                if (task.IsCompleted)
                    taskBools = "Task Completed";
                else if (task.IsFaulted)
                    taskBools = "Task Faulted";
                else if (task.IsCanceled)
                    taskBools = "Task Canceled";

                string taskStatus = task.Status.ToString();
                msg = $"Task Status: {taskBools} taskStatus: {taskStatus}";

                ApplicationLogger.Singleton.LogMessage(LogCategories.General, System.Diagnostics.TraceEventType.Verbose, msg, "Task Status");

                string listOfSites = (string)task.Result;
                ApplicationLogger.Singleton.LogMessage(LogCategories.General, System.Diagnostics.TraceEventType.Verbose, 
                    $"listOfSites: {listOfSites}", "GetUrlResponseString - listOfSites");

                return listOfSites;
            }
在您的站点和其他站点上,我们看到提到了SecurityProtocolType.SystemDefault。根据我的研究,我们希望使用它,因为它应该从操作系统获得安全设置。我们希望我们的服务器管理员来处理这个问题。这样我们以后就不必更改代码了

现在我知道,当.Net支持Tls13、Tls14等时,我们可能需要重新编译和部署类库,但它仍然消除了代码更改


无论如何,我们的服务器管理员无法让它使用SecurityProtocolType.SystemDefault设置。她想知道程序认为当前的安全设置是什么。是否有我无法检查/打印的内容?

默认为
Ssl3
Tls1.0
。如果您有
.netframework4.7.2
,则
HttpClientHandler
可以
获取;设置它的属性,在运行时可读。4.7.1具有该属性,但未实现。关于4.7.1,您是对的。使用4.7.2 strslprotocols=clientHandler.SslProtocols.ToString()尝试了这一点;说明:Ssl握手失败后,日志中没有?如果是这样,不幸的是HttpClient在事务被拒绝时没有设置响应。您必须获取底层的
ConnectStream
才能访问
NetworkStream
SslProtocol
。我在这里发布了一个获取协商Ssl协议的方法:
(…)
。您可以做的一件肮脏的事情是启用所有协议(它们是标志),组合所有可用的枚举值,然后让Ssl握手决定使用哪一个。协商成功终止后,请检查已商定的协议,如果不喜欢,请断开连接。我有一种预处理器方法,它根据不同的条件(连接尝试之前和之后)设置Ssl协议。为此,您需要有一个静态HttpClient设置,可能是在惰性(
Lazy
)构造函数/配置中。