System.AggregateException
HResult = 0x80131500
Message =发生一个或多个错误。
来源= System.Private.CoreLib
堆栈跟踪:
在System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
内部例外1:
HttpRequestException:无法建立SSL连接,请参阅内部异常。
内部例外2:
IOException:无法从传输连接中读取数据:现有连接被远程主机强行关闭。
内部例外3:
SocketException:现有连接被远程主机强行关闭
[复制到剪贴板] |
class Program
{
static void Main(string[] args)
{
var url = "https://google.com";
var (statusCode, html) = requestString(url);
Console.WriteLine("%d %s", statusCode, html);
}
static CookieContainer cc = new CookieContainer();
static HttpClientHandler handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cc };
public static async Task<(int statusCode, string content)> requestStringAsync(string url)
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
// | SecurityProtocolType.Ssl3;
using (var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = HttpMethod.Get })
using (var client = new HttpClient(handler))
{
var response = await client.SendAsync(request); // Error (actual line)
var statusCode = (int)response.StatusCode;
var content = await response.Content.ReadAsStringAsync();
return (statusCode, content);
}
}
public static (int statusCode, string content) requestString(string url)
{
return requestStringAsync(url).Result;
}
}
按上面调整 ServicePointManager 后在 .net framework环境中就可以正常运行了。
在.Net Core的环境中还可能发生问题。
.Net Core中可以使用以下机制之一来配置进程以使用较旧的HttpClientHandler:
从代码中,使用AppContext类:
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
也可以通过配置文件来设置AppContext开关。
可以通过环境变量DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER实现相同的目的。
要选择退出,请将值设置为false或0。