Forcing SSL on ASP.NET from http to https and vice-versa

SSL

Lets assume we have a shopping chart web app, to create a safe environment for your buyers you need to run the payment page on https. So here is what we will need to do….

In your master page (assuming you have one), read through and paste the following code in the page load or page init:

protected void Page_Load(object sender, EventArgs e)
{

//if on https, secure = true;

bool secure = HttpContext.Current.Request.IsSecureConnection;

//Path of the page which requires SSL (https) – CHANGE TO OWN PATH

string paymentPagePath = “/PaymentGateway/default.aspx”;

// Server name or localhost if running locally

string serverName = Request.ServerVariables[“SERVER_NAME”];

// Path of the current page
string scriptName = Request.ServerVariables[“SCRIPT_NAME”];

// Query String if any
string queryString = Request.ServerVariables[“QUERY_STRING”];

// If we are on the page which requires SSL
if (absolutePath.Contains(paymentPagePath))
{

// If it is not currently using https
if (!secure)
{

if (Request.ServerVariables.Get(“HTTP_CLUSTER_HTTPS”) == null)
{

string xredir__, xqstr__;

// Build redirect Link using https 

xredir__ = “https://” + serverName;
xredir__ += scriptName;
xqstr__ = queryString;

if (xqstr__ != “”)
xredir__ = xredir__ + “?” + xqstr__;

// Redirect to same page using https

Response.Redirect(xredir__);

}

}

}

 // else if not of page which requires SSL

// if page is using SSL, we need to redirect to http
else if (secure)
{

string xredir__, xqstr__;

xredir__ = “http://” + serverName;
xredir__ += scriptName;
xqstr__ = queryString;

if (xqstr__ != “”)
xredir__ = xredir__ + “?” + xqstr__;

// Redirect to same page using http and not https

Response.Redirect(xredir__);

}

}