Postman http 请求成功,SSL/TLS 安全通道的 C# HttpWebRequest 错误信任关系

Postman http request success, C# HttpWebRequest error trust relationship for the SSL/TLS secure channel

相关文章但未解决问题:


总结

尝试使用基本 HttpWebRequest 在 C# 中请求时,returns 错误:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel., System.Security.Authentication.A uthenticationException: The remote certificate is invalid according to the validation procedure.

但使用 Postman 向第三方请求时 API,returns 成功。


实际代码:

Console.WriteLine("---START---");

var url = "https://" + ConfigurationManager.AppSettings["ClientDNS"].ToString() + ConfigurationManager.AppSettings["ClientTokenUri"].ToString();
var redirect = ConfigurationManager.AppSettings["UserRedirect"].ToString();
var clientId = ConfigurationManager.AppSettings["ClientId"].ToString();
var code = ConfigurationManager.AppSettings["ClientCode"].ToString();
var result = "";

Console.WriteLine(string.Format("url : {0}\n", url));
Console.WriteLine(string.Format("redirect : {0}\n", redirect));
Console.WriteLine(string.Format("clientid : {0}\n", clientId));
Console.WriteLine(string.Format("code : {0}\n", code));

try
{
    ServicePointManager.Expect100Continue = true;
    ServicePointManager.DefaultConnectionLimit = 9999;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls 
        | SecurityProtocolType.Tls11 
        | SecurityProtocolType.Tls12 
        | SecurityProtocolType.Tls13
        | SecurityProtocolType.Ssl3;

    //As suggested by Ali Bahrami
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

    var postData = "grant_type=authorization_code&redirect_uri=" + redirect + "&code=" + code + "&client_id=" + clientId;

    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    // Update base from link 01
    httpWebRequest.Method = "POST";
    httpWebRequest.AllowAutoRedirect = true;
    httpWebRequest.Timeout = 20 * 1000;
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
    httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36";

    byte[] buffer = Encoding.Default.GetBytes(postData);
    if (buffer != null)
    {
        httpWebRequest.ContentLength = buffer.Length;
        httpWebRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
    }

    Console.WriteLine("getting response");
    var response = (HttpWebResponse)httpWebRequest.GetResponse();
    result = string.Format("result: {0}\n", new StreamReader(response.GetResponseStream()).ReadToEnd());

}

catch (Exception ex)
{
    result = string.Format("result: {0}\n", ex.Message + (ex.InnerException != null ? ", " + ex.InnerException : ""));
}

link 01 -

我认为由于使用 self-signed 证书,ServicePointManagerServer 无法验证您的证书。正如我在评论中所建议的那样,您需要编写一种方法来更改您的案例中的这种行为。

解决方法之一是在验证发生时 return 为真:

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

当然,有些人在 real-world 情况下不赞成此解决方法,因为您实际上禁用了证书验证。但是,如果您正在处理内部 Web 服务,只需使用上述方法忽略验证。