为什么代码在c#Interactive(Roslyn)和debug \ release模式下表现不同?

时间:2017-01-30 23:30:52

标签: c# https webclient tls1.2

更新 实际上在挖掘网络监控之后,我发现执行Roslyn的代码和正常的调试\发布模式的方式有所不同。 在调试\发布模式下Fiddler跟踪错误:

[Fiddler] The connection to 'host.com' failed.  <br/>System.Security.SecurityException Failed to negotiate HTTPS connection with server.fiddler.network.https&gt; 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. &lt; 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)

请求建议

1 个答案:

答案 0 :(得分:1)

解决方案

我认为C#interactive以某种方式预配置,它能够将ServicePointManager.SecurityProtocol默认为旧版本。作为我添加到代码中的解决方案:

using System.Net;
....
ServicePointManager.SecurityProtocol = 
       SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;