更新实际上,在挖掘网络监控之后,我发现执行的代码Roslyn和正常的调试\发布模式发出请求的方式有所不同。在调试\发布模式下,提琴手跟踪错误:
[Fiddler] The connection to 'host.com' failed. <br/>System.Security.SecurityException Failed to negotiate HTTPS connection with server.fiddler.network.https> HTTPS handshake to host.com (for #76) failed. System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. < An existing connection was forcibly closed by the remote host
原始问题:我得到了一段代码:
HttpTransportOverWebClient c = new HttpTransportOverWebClient();
c.GetURL("https://web.page/query")
其中 GetUrl 是一些包装器:
public bool GetURL(string URL)
{
try
{
web.Headers.Add("User-Agent", browserAgent);
byte[] data = web.DownloadData(URL);
string characterSet = web.Response.CharacterSet;
string encoding = (characterSet == null || characterSet == "" || characterSet.ToUpper() == "NONE") ? "UTF-8" : web.Response.CharacterSet.ToUpper();
html = Encoding.GetEncoding(encoding).GetString(data);
return true;
}
catch (Exception ex)
{
lastException = web.LastException == null ? new WebException(ex.Message) : web.LastException;
}
return false;
}
C#交互模式下的行为:
GetURL 返回 true 和 html 包含数据
调试\发布模式下的行为:
GetURL 返回 false 和 ex 包含以下错误:
An exception occurred during a WebClient request.
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadData(Uri address)
at HttpCrawler.HttpTransportOverWebClient.GetURL(String URL) in ..HttpTransportOverWebClient.cs:line xx
内部异常:
at System.Net.WebClient.DownloadBitsState.SetResponse(WebResponse response)
at System.Net.WebClient.DownloadBits(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp)
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
恳求建议
解决方案
我想C#交互式以某种方式预先配置,它能够将ServicePointManager.SecurityProtocol默认为旧版本。作为解决方案,我添加到代码中:
using System.Net;
....
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;