首页 > 解决方案 > 带有证书的 C# HTTPS Post

问题描述

我需要帮助在 C# 中使用证书设置 HTTP 帖子。

我收到一个错误:

"The underlying connection was closed: An unexpected error occurred on a send'. 谢谢你。网络框架是 4.5

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = TrustCertificate;
byte[] bytes = new ASCIIEncoding().GetBytes(transaction);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlString);
request.ClientCertificates.Add(new X509Certificate());
request.Method = "POST";
string str = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + pwd));
request.Headers["Authorization"] = "Basic " + str;
request.ContentType = "text/xml";
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string str2 = reader.ReadToEnd();
response.Close();
reader.Close();
return str2;

标签: sslhttpscertificate

解决方案


该错误可能有几个原因。这是我的诊断清单。

  1. 使用浏览器(使用 Windows 证书存储 - IE 或 Chroms)进行GET请求,或使用Fiddler处理所有其他 HTTP 动词(POST, ...)来调用端点。
  2. 确保服务器证书有效(NotBefore & NotAfter)并且未被撤销。浏览器将显示错误并提供详细信息。
  3. 检查客户端和服务器匹配的 TLS/SSL 版本。IISCrypto(名称令人困惑)显示客户端和服务器上的平台配置(Windows SCHANNEL)。此外,还有一个不错的 PowerShell 脚本,可以打开与所有 TLS/SSL 版本的连接。如果您无权访问服务器但它是公开可用的,您可以使用https://www.ssllabs.com/ssltest/analyze.html检查支持哪些 TLS 版本
  4. 最后但并非最不重要的一点是确保客户端和服务器可以协商密码套件。IISCryptohttps://www.ssllabs.com/ssltest/analyze.html也可以显示支持的密码套件。

编辑

用firefox检查,证书没问题,不是自签名(DigiCert): 在此处输入图像描述

使用 TLS 1.2 对提供的 URL 运行 get 请求:

try {
  var urlString = "https://www.viewmyrecord.com/";
  ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  var request = (HttpWebRequest) WebRequest.Create(urlString);
  request.ClientCertificates.Add(new X509Certificate());
  request.Method = "GET";

  using (var response = (HttpWebResponse) request.GetResponse()) {
    Console.WriteLine(response.StatusCode);
  }
} catch (Exception ex) {
  Console.ForegroundColor = ConsoleColor.Red;
  Console.WriteLine(ex.ToString());
  Console.ResetColor();
}

从这里开始工作:

在此处输入图像描述


推荐阅读