是否可以在.NET 4.0框架上使用TLS1.2发送HttpWebRequest

gen*_*ene 34 c# .net-4.0 httpwebrequest .net-4.5 tls1.2

我的应用程序连接到Experian服务器,Experian将很快停止支持HttpWebRequestwebservice.使用所有连接HttpWebRequest必须使用webservice.

我想对这个问题进行一些研究,看看在工作中发送HttpWebRequest使用webserviceHttpWebRequest

如果没有,我可能需要创建一个webserviceon HttpWebRequest并调用它的方法,如果有的话,我没有任何东西.

有人已经面临过这个问题吗?

Cro*_*der 77

是的,它支持它但你必须在上面明确设置TLS版本ServicePointManager.只需在调用Experian之前随时(在相同的应用程序域中)运行此代码:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
Run Code Online (Sandbox Code Playgroud)

更新

请参阅@iignatov的答案,了解您必须为框架v4.0做些什么.我的代码适用于4.5+

  • @AgustinGarzon如果你想支持其他版本,你可以"或"将它们放在一起,如:`SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls10` (5认同)
  • 如果你想面向未来,你不应该显式设置它 = ,而是添加它 w/ |= - 即。System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12 (4认同)

小智 30

我不得不处理同样的问题,同时将PayPal集成到遗留应用程序中,并发现.NET 4.0的以下解决方法似乎可以解决这个问题:

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.DefaultConnectionLimit = 9999;
Run Code Online (Sandbox Code Playgroud)

基本上,解决方法是直接为TLS 1.2分配端口.

所有功劳都归功于CodeProject的评论者.

  • 仅当服务器上还安装了.net 4.5时,hack才有效。 (2认同)

小智 6

iignatov 答案的 VB.NET 翻译:

ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
ServicePointManager.DefaultConnectionLimit = 9999
Run Code Online (Sandbox Code Playgroud)


Sed*_*mcu 5

我是用这个方法解决的。

    string url = "https://api.foursquare.com/v2/blablabla...";
    var request = (HttpWebRequest)WebRequest.Create(url);

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
    
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Run Code Online (Sandbox Code Playgroud)