ServicePointManager SecurityProtocol冲突

lng*_*lng 10 .net c# system.net.mail restsharp

在我的应用程序中,我使用RestSharp查询REST API和System.Net.Mail来发送电子邮件.在程序启动时,我设置了ServicePointManager.SecurityProtocol属性.

如果我将属性设置为:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
Run Code Online (Sandbox Code Playgroud)

使用RestSharp查询API时抛出异常:

The request was aborted: Could not create SSL/TLS secure channel
Run Code Online (Sandbox Code Playgroud)

如果我将属性设置为:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
Run Code Online (Sandbox Code Playgroud)

使用System.Net.Mail发送电子邮件时抛出异常:

System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The client and server cannot communicate, because they do not possess a common algorithm
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Mår*_*röm 7

REST API服务器和您要连接的邮件服务器显然具有冲突的安全协议要求.您需要为它们使用不同的安全协议设置.

ServicePointManager.SecurityProtocol是静态的,其当前值适用于所有新连接.遗憾的是,无法为每个ServicePoint控制此设置.(在我看来,这是微软的设计缺陷)

如果您可以控制REST API服务器或邮件服务器,那么您可以重新配置它们以接受非冲突的安全协议.

否则,您可以重新设计代码,以便与REST API和邮件服务器的所有连接都来自两个单独的AppDomain.

例如,让默认应用程序域处理所有REST API通信,并生成一个单独的应用程序域,用于执行所有邮件通信.

使用此设置,您可以在每个域中使用不同的ServicePointManager.SecurityProtocol值.(因为应用程序域之间不共享静态值).