前几天在做一个使用URL通过WebRequest请求HTML页面的功能的时候遇到了点坑,程序在开发环境没有任何的问题,部署到linux mono上之后就跪了。代码如下:

public static string GetHTML(string url)
{
string htmlCode;
try
{
HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
webRequest.Timeout = 30000;
webRequest.Method = "GET";
webRequest.UserAgent = "Mozilla/4.0";
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
//获取目标网站的编码格式
string contentype = webResponse.Headers["Content-Type"];
Regex regex = new Regex("charset\\s*=\\s*[\\W]?\\s*([\\w-]+)", RegexOptions.IgnoreCase);
if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
{
using (System.IO.Stream streamReceive = webResponse.GetResponseStream())
{
using (var zipStream = new System.IO.Compression.GZipStream(streamReceive,
System.IO.Compression.CompressionMode.Decompress))
{
//匹配编码格式
if (regex.IsMatch(contentype))
{
Encoding ending = Encoding.GetEncoding(regex.Match(contentype).Groups[1].Value.Trim());
using (StreamReader sr = new System.IO.StreamReader(zipStream, ending))
{
htmlCode = sr.ReadToEnd();
}
}
else
{
using (StreamReader sr =
new System.IO.StreamReader(zipStream, Encoding.UTF8))
{
htmlCode = sr.ReadToEnd();
}
}
}
}
}
else
{
using (System.IO.Stream streamReceive = webResponse.GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.Default))
{
htmlCode = sr.ReadToEnd();
}
}
}
return htmlCode; }catch(Exception ex)
{
LogHelper.WriteException("GetHTML", ex, new { Url = url });
return "";
} }

无论是HTTP还是HTTPS协议,网页HTML一样能获取得到。开发环境在Windows10 + VS2013,整个代码跑起来没什么问题。

网站部署到linux Jexus之后HTTP协议的网站同样可以获取到HTML,遇到HTTPS协议的网站的时候就跪了。

抓到的异常信息如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
System.Net.WebException: Error: TrustFailure (The authentication or decryption has failed.) 
---> System.IO.IOException: The authentication or decryption has failed.
---> System.IO.IOException: The authentication or decryption has failed.
---> Mono.Security.Protocol.Tls.TlsException:
Invalid certificate received from server. Error code: 0xffffffff800b0109
at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord
(IAsyncResult asyncResult) <0x41b58d80 + 0x0013e> in <filename unknown>:0
at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord
(IAsyncResult ar, Boolean ignoreEmpty) <0x41b58cb0 + 0x00031> in <filename unknown>:0
at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker
(IAsyncResult result) <0x41b72a40 + 0x0023f> in <filename unknown>:0
--- End of inner exception stack trace ---
at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake
(IAsyncResult result) <0x41ba07e0 + 0x000f3> in <filename unknown>:0
at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback
(IAsyncResult asyncResult) <0x41ba0540 + 0x00086> in <filename unknown>:0
--- End of inner exception stack trace ---
at Mono.Security.Protocol.Tls.SslStreamBase.EndRead
(IAsyncResult asyncResult) <0x41b73fd0 + 0x00199> in <filename unknown>:0
at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient
(IAsyncResult asyncResult) <0x41b73f30 + 0x00042> in <filename unknown>:0
at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost,
System.Security.Cryptography.X509Certificates.X509CertificateCollection
clientCertificates, SslProtocols enabledSslProtocols,
Boolean checkCertificateRevocation) <0x41b6a660 + 0x00055> in <filename unknown>:0
at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer)
<0x41b69c30 + 0x00159> in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
<0x41b67660 + 0x001f9> in <filename unknown>:0
at System.Net.HttpWebRequest.GetResponse () <0x41b60920 + 0x0005a> in <filename unknown>:0
at WebBookmarkUI.Commom.HTTPHelper.GetHTML (System.String url) <0x41b59b70 + 0x00235>
in <filename unknown>:0

有用的信息基本就是:

  1. Invalid certificate received from server
  2. The authentication or decryption has failed

一开始百思不得其解,为嘛好好的程序在开发环境跑得都好的,到了mono上就挂了,多疑的我还以为是mono的bug。
今天静下心来去找了一下资料,发现Mono的文档有这个问题的描述,认真读了一遍,又去请教了一番宇内流云大大,终于弄懂了是什么回事。

先贴一下相关资料:

  1. stackoverflow mono-webrequest-fails-with-https

  2. mono doc security

这个问题是出现的原因是Windows自带了HTPPS的根证书,linux默认则是没有带有根证书的。我们的mono在调用WebRequest去请求HTTPS协议的网站的时候,找不到任何有效的根证书,所以抛出上面的异常了。

解决方案也很简单,为linux导入一下HTTPS根证书就好。

在linux服务器上面执行下面这条命令。

mozroots --import --ask-remove --machine

然后在网站的Application_Start()里面添加下面代码:

1
2
3
4
5
6
7
 System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true; // **** Always accept
};

完事。

这个故事告诉我们,linux干活都是要亲力亲为呀。

原文首发于:codelover.link

mono webreques https exception的更多相关文章

  1. mono的https使用使用事项

    private static void SetCertificatePolicy() { if( ServicePointManager.ServerCertificateValidationCall ...

  2. jexus5.8.2 linux x64通用版[未集成mono] 配置https

    一.找到mono安装位置 sudo find / -name mono 二.首先查看"/lib"或"/usr/lib"等系统库文件夹中是否有SSL库文件的名字, ...

  3. jexus linux x64[标准版] - 未集成mono 配置https

    一.找到mono安装位置 sudo find / -name mono 二.首先查看“/lib”或“/usr/lib”等系统库文件夹中是否有SSL库文件的名字,该文件名应该是“libssl.so.版本 ...

  4. Java调用Http/Https接口(7,end)--WebClient调用Http/Https接口

    WebClient是Spring提供的非阻塞.响应式的Http客户端,提供同步及异步的API,将会代替RestTemplate及AsyncRestTemplate.文中所使用到的软件版本:Java 1 ...

  5. Mono提供脚本机制(C#绑定C++)

    1.下载安装最新版mono,https://www.mono-project.com/ 2.添加头文件路径C:\Program Files\Mono\include\mono-2.0,添加库路径C:\ ...

  6. VS2013中的MVC5模板部署到mono上的艰辛历程

    部署环境:CentOS7 + Mono 3.10 + Jexus 5.6 在Xamarin.Studio创建的asp.net项目,部署过程非常顺利,没有遇到什么问题:但在VS2013中创建的asp.n ...

  7. 从Unity3D编译器升级聊起Mono

    接前篇Unity 5.3.5p8 C#编译器升级,本文侧重了解一些Mono的知识. Unity3D的编译器升级 新升级的Mono C#编译器(对应Mono 4.4) Unity编辑器及播放器所使用的M ...

  8. Unity Mono脚本 加密

    加密环境 引擎版本:Unity3D 5.3.4 及更高版本 (使用Mono而并非IL2CPP) 操作系统:CentOS 6.2(Final) 加密环境:Android.IOS(暂定) 加密对象:C#源 ...

  9. MVC5模板部署到mono

    VS2013中的MVC5模板部署到mono上的艰辛历程 2014-10-27 09:30 by FuzhePan, 3954 阅读, 46 评论, 收藏, 编辑 部署环境:CentOS7 + Mono ...

随机推荐

  1. Uva 11419 我是SAM

    题目链接:https://vjudge.net/problem/UVA-11419 题意:一个网格里面有一些目标,可以从某一行,某一列发射一发子弹,可以打穿: 求最少的子弹,和在哪里打? 分析: 听说 ...

  2. python 3+djanjo 2.0.7简单学习(五)--Django投票应用

    1.编写一个简单的表单 编写的投票详细页面的模板 ("votes/detail.html") ,让它包含一个 HTML <form> 元素: <!DOCTYPE ...

  3. XCode项目配置可访问 非 https 接口的方法

    打开项目的info.plist文件,右键- open as sourceCode .在代码中添加: <key>NSAppTransportSecurity</key> < ...

  4. out 和ref 的区别

    练习 1: 练习 2: 练习 3:

  5. Python 学习笔记(七)Python字符串(三)

    常用字符串方法 split()  分割字符串,指定分隔符对字符串进行分割 join()   将序列中的元素以指定的字符连接生成一个新的字符串 str.strip() 用于移除字符串头尾指定的字符(默认 ...

  6. 使用RMAN对数据文件进行恢复

    (1)备份数据库 在使用RMAN进行数据库恢复之前,先用RMAN进行全库备份 [oracle@redhat6 ~]$ rman target / Recovery Manager: Release : ...

  7. xcode7--iOS开发---将app打包发布至app store

    时隔3个月再次接触应用打包,又是一顿折腾 说说这次的感受吧: 变得是打包时间减少到4小时(其中大部分时间还是xcode7或者是iOS9的原因),不变的是还是一如既往的坑!! 好了,废话不多说,下面讲讲 ...

  8. ios断点续传:NSURLSession和NSURLSessionDataTask实现

    苹果提供的NSURLSessionDownloadTask虽然能实现断点续传,但是有些情况是无法处理的,比如程序强制退出或没有调用 cancelByProducingResumeData取消方法,这时 ...

  9. 车站分级 (2013noip普及组T4)(树形DP)

    题目描述 一条单向的铁路线上,依次有编号为 1,2,…,n 的 n个火车站.每个火车站都有一个级别,最低为 1 级.现有若干趟车次在这条线路上行驶,每一趟都满足如下要求:如果这趟车次停靠了火车站 x ...

  10. linux命令系列-ln(软硬链接)

    linux命令 ln命令可以生成软链接和硬链接,也可叫做符号链接和实体链接. 有兴趣深入理解的可以查阅相关文档,一般的读者只需记住以下几点即可: .不管是软链接还是硬链接都不会额外增加磁盘空间(虽然实 ...