在我的 C# Windows 客户端中,我有一个 POST 提交到“母舰”。当然,我希望提交的数据得到保护,所以我支付了 HostGator 的费用来给我颁发 SSL 证书。
我保存了 .CER 文件,并且正在构建请求:
//wrapper for WebClient object to use certificate file
class SecureWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
string certPath = @"e:\mycertificate.cer";
X509Certificate myCert = X509Certificate.CreateFromCertFile(certPath);
request.ClientCertificates.Add(myCert);
return request;
}
}
//request
private static SecureWebClient client = new SecureWebClient();
private static NameValueCollection = new NameValueCollection();
nvc.Add(POST_ACTION, ACTION_CODE_LOGIN);
nvc.Add(POST_EMAIL, email);
nvc.Add(POST_PASSWORD, password);
sResponse = System.Text.Encoding.ASCII.GetString(client.UploadValues(BASE_URL + ACTION_PAGE, nvc));
它抛出 System.Net.WebException:
The underlying connection was closed: An unexpected error occurred on a send.
InnerException 是一个 System.IO.IOException:
The handshake failed due to an unexpected packet format.
对我做错了什么有任何见解吗?
最佳答案
如果您不使用客户端证书并且您可以使用https://访问您的服务器那么你的代码应该是这样的:
private static WebClient client = new WebClient();
private static NameValueCollection nvc= new NameValueCollection();
nvc.Add(POST_ACTION, ACTION_CODE_LOGIN);
nvc.Add(POST_EMAIL, email);
nvc.Add(POST_PASSWORD, password);
sResponse = System.Text.Encoding.ASCII.GetString(client.UploadValues(BASE_URL + ACTION_PAGE, nvc));
只要您的BASE_URL 使用https://,那么所有数据(进出服务器)都将被加密。
除了使用 https:// 作为方案之外,从客户端到服务器使用 SSL/TLS 的 IOW 不需要客户端做任何特殊的事情(使用证书),因为操作系统提供保护数据传输所需的一切(例如可信根)。
关于c# - 使用带有 HTTPS 证书的 System.Net.WebClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7402752/