Monday, August 29, 2011

ASP.NET: Automatically convert http urls into https url

Sometimes we need to navigate securely within the website because of some confidential information. The user might use just http but we need to change it into https. So the approach I like best is to do it in masterpage level. We can write a small code snippet in the page load section of the masterpage which checks if the page is http or not. If it is http then changes it to https. Following are the line of codes that we need to put in the master page's page load function. I did not come up with these code, I collected it from the internet. So I am not taking any credit for the code ;)

//Redirect to https if typed http.

string redirectUrl = null;
HttpContext context = HttpContext.Current;

// if we want HTTPS and it is currently HTTP
if (!context.Request.IsSecureConnection)
{
redirectUrl = context.Request.Url.ToString().Replace("http:", "https:");
}

// check if we need to redirect, and if so use redirectUrl to do the job
if (redirectUrl != null)
context.Response.Redirect(redirectUrl);

Hope it helps. :)

No comments:

Post a Comment