起因:
之前拿到过别人开发的一套采集程序源代码,几年前也自己改过部分代码,用着都还好。最近有一个新的业务需求,感觉那套程序比较适合,想拿来再改改。结果各种报错 比如“”基础连接已经关闭: 发送时发生错误。“”。先是发现获取不到网页源代码,但是之前的代码程序【抓取http页面】还能跑,新的需求是https页面,我以为是单纯https的原因。于是到网上各种搜C# https的解决方案,找到的方案主要有以下几种:
1. request.ProtocolVersion = HttpVersion.Version10;
2. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
3.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
4.换个UserAgent试试
5.在App.config中添加以下内容:
<system.net> <settings> <httpWebRequest useUnsafeHeaderParsing="true"/> </settings> </system.net>
试了以上的方法,还是不能用,特别的烦躁。后来又测试了一下获取https://www.baidu.com/ ,能获取到源代码。于是怀疑是https具体协议种类的问题,查了一下ms的文档,发现ssl已经不作为推荐协议种类。而TLS1.2正是我们要抓取的网站使用的https协议。
于是又Google了一下【码农还是得靠google】,得到以下解决方案:
- .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default. 原来 .net 4.6及以上默认支持,不需要添加额外代码。
- .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource: 翻译: .net 4.5系列支持TLS1.2,但是在发起request之前需要添加额外的代码
1 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12- .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value: 中文:.net4.0 是不支持TLS1.2的【坑爹,我就是用的4.0】,但是有曲线救国的方法。如下
1 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;- .NET 3.5 or below. TLS 1.2 is not supported (*) and there is no workaround. Upgrade your application to more recent version of the framework. .net3.5及以下完全不支持。