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

问题描述 投票:32回答:5

我的应用程序连接到Experian服务器,Experian将很快停止支持TLS 1.0和TLS 1.1。使用HTTPS的所有连接必须使用TLS版本1.2。

我想对这个问题做一些研究,看看在.NET 4.0框架上使用TLS 1.2发送HttpWebRequest

如果没有,我可能需要在.NET 4.5上创建一个webservice并调用它的方法,如果有的话,我没有任何东西。

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

c# .net-4.0 httpwebrequest .net-4.5 tls1.2
5个回答
73
投票

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

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

更新

请参阅@iignatov 's answer,了解框架v4.0必须做的事情。我的代码适用于4.5+


28
投票

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

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.DefaultConnectionLimit = 9999;

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

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


2
投票

iignatov's answer的VB.NET翻译:

ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
ServicePointManager.DefaultConnectionLimit = 9999

0
投票

不幸的是,你不能这样做。直到.netfx 4.5才添加Tls12(参见the documentation)。请注意,这还需要Windows Server 2008 R2 +或Windows 7+才能正常运行(请注意Introducing TLS上的“适用于”部分)。


0
投票

FrameWork 4.0不支持TLS 1.1或1.2但您可以通过从Nuget管理器下载Rebex.Http来解决此问题。

Rebex.Licensing.Key = "..."; //Lisans Number
var creator = new HttpRequestCreator();
creator.Register();

WebRequest request = WebRequest.Create("https://www.test.com");
request.Method = "POST";                
request.Headers.Add("utsToken", txtToken.Text);
request.ContentType = "application/json";
request.Method = "POST";

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
    string json = "{\"VRG\":\"test\"}";

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (WebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
    txtSonuc.Text += result;
}

0
投票

你也可以用这个:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
© www.soinside.com 2019 - 2024. All rights reserved.