Tuesday, September 15, 2009

Form POST using HttpWebRequest but on SSL

In my last post i presented the code snippet for posting form data using HttpWebRequest with POST method.. It was working fine until the page I was accessing, transferred to SSL and my application ended up with "The underlying connection was closed: Could not establish trust relationship with remote server." exception.  Without going through MSDN i logged in to forums.asp.net and guess what? yeah found the solution...
Just create a Certificate Policy which accept all Certificates...bus!

public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{ }


public bool CheckValidationResult(ServicePoint sp,
X509Certificate cert, WebRequest req, int problem)
{
return true;
}
}

As you can see CheckValidationResult always return true thus accepting all certificates...

To use this CertificatePolicy, you'll have to tell the ServicePointManager to use it:
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
...............................................

Thanks to:
http://weblogs.asp.net/jan/archive/2003/12/04/41154.aspx

No comments:

Post a Comment