ASP.NET Web Request POST/GET HTTPS Ignore Certificate Validation
Posted by in CSharp September 22, 2011 Leave a comment

To make a web request to a remote URL via HTTPS protocol, it’s required more works than via HTTP because it need to validate the SSL Certificate. If you have any issue with the certificate (invalid, expired or unstrusted), you programming may doesn’t work. Likely when you browse a particular website with HTTPS, you could be notified some thing: “There is a problem with this website’s security certificate.“, “This Connection is Untrusted” or “The site’s security certificate is not trusted!

IE SSL Certificate Issue

IE SSL Certificate Issue

Therefore, the easiest solution is accepting all SSL certificate although it may less secure but most importantly, it works :)

Example post data to HTTPS in asp.net

An example below will try to send a post request to a remote website via a HTTPS URL, it will accept all certificates to make sure it works.

using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
 
public partial class https_request : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = "https://4rapiddev.com";
        Response.Write(MakeRequest(url));
    }
 
    private static bool ValidateRemoteCertificate(
    object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors policyErrors
    )
    {
        return true;
    }
 
    private static string MakeRequest(string uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
        webRequest.AllowAutoRedirect = true;
        webRequest.Method = WebRequestMethods.Http.Post;
 
        ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
            ValidateRemoteCertificate
        );
 
        string output = "";
 
        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)webRequest.GetResponse();
 
            StreamReader reader = new StreamReader(response.GetResponseStream());
            output = reader.ReadToEnd();
            response.Close();
        }
        finally
        {
            if (response != null)
                response.Close();
        }
 
        return output;
    }
}

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com