In a .NET development, if you try to connect to the remote server through a web service with SSL you will probably get the following error message:
"The underlying connection was closed: Could not establish trust
relationship for the SSL/TLS secure channel."
inner Exception.Message is:
"The remote certificate is invalid according to the validation procedure."
To solve this problem, simply add a line of code which is underlined in red.
Required namespace:
System.Net;
Code:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
This code simple bypass all the certificate validation check, include invalid and expired certificates.Sample Code:
// callback used to validate the certificate in an SSL conversation
private static bool ValidateRemoteCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors policyErrors
)
{
if (Convert.ToBoolean(ConfigurationManager.AppSettings["IgnoreSslErrors"]))
{
// allow any old dodgy certificate...
return true;
}
else
{
return policyErrors == SslPolicyErrors.None;
}
}
private static string MakeRequest(string uri, string method, WebProxy proxy)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.AllowAutoRedirect = true;
webRequest.Method = method;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
ValidateRemoteCertificate
);
if (proxy != null)
{
webRequest.Proxy = proxy;
}
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)webRequest.GetResponse();
using (Stream s = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(s))
{
return sr.ReadToEnd();
}
}
}
finally
{
if (response != null)
response.Close();
}
}
Reference:
http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx
No comments:
Post a Comment