I have code that makes a server side call to another web service. In many situations this is over SSL. We have problems where this fails when the stars are not completely aligned. I realize that the certificate must be trusted and the internal certificate authorities (CAs) likely have to be manually imported into the trusted root certificate store on the servers. However, there are other cases as well. Today I ran into a problem where if I use a browser to hit the URL I get a warning stating that:
The na开发者_开发知识库me on the security certificate is invalid or does not match the name of the site
This is just a warning that you can acknowledge with the browser and tell it to continue to the site.
However, it seems to prevent my code from working. Here is a condensed version of my code:
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = new NetworkCredential(user, password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
In looking at HttpWebRequest I don't see anything obvious that would help me out and I don't currently have the luxury of trying things out in my developer environment. Is there a simple change I can make to fix this? Are there other similar gotchas I can prevent this way as well?
Kirk, have you looked into using ServerCertificateValidationCallback and simply returning true (as a test) and then augmenting the error checking for the special cases? You can also check out What is the best way of handling non-validating SSL certificates in C# for some other info on checking cer
Working solution:
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = new NetworkCredential(user, password);
ServicePointManager.ServerCertificateValidationCallback = delegate(object certsender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
See also SSLPolicyErrors for the enumeration to review in the delegate.
精彩评论