ssl - 带有证书的 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;
解决方案
该错误可能有几个原因。这是我的诊断清单。
- 使用浏览器(使用 Windows 证书存储 - IE 或 Chroms)进行
GET
请求,或使用Fiddler处理所有其他 HTTP 动词(POST
, ...)来调用端点。 - 确保服务器证书有效(NotBefore & NotAfter)并且未被撤销。浏览器将显示错误并提供详细信息。
- 检查客户端和服务器匹配的 TLS/SSL 版本。IISCrypto(名称令人困惑)显示客户端和服务器上的平台配置(Windows SCHANNEL)。此外,还有一个不错的 PowerShell 脚本,可以打开与所有 TLS/SSL 版本的连接。如果您无权访问服务器但它是公开可用的,您可以使用https://www.ssllabs.com/ssltest/analyze.html检查支持哪些 TLS 版本
- 最后但并非最不重要的一点是确保客户端和服务器可以协商密码套件。IISCrypto和https://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();
}
从这里开始工作:
推荐阅读
- github - 如何从 Github API V3 上的发布或标签获取提交 SHA
- c - C中的快速排序——指针和内存
- django - 从 django 发送邮件失败
- javascript - 填写字段时使用 JavaScript 弹出 SweetAlert 消息
- sql - SQL Server 案例更新
- java - 不可分配给 android.app.application
- c - 如何修复“postgres.h”文件未找到问题?
- git - 重置命令后强制推送 git 提交不起作用
- react-native - undefined 不是对象(评估“response.data”)
- php - 不能在 Eloquent Query Builder 宏中使用“with”