Detecting HTTP vs HTTPS in ASP.NET

One simple command will let you know if the user is accessing your page via SSL.

Request.IsSecureConnection

Example

if (Request.IsSecureConnection)
{
    Response.Write("HTTPS");
}
else
{
    Response.Write("HTTP");
}

Redirecting to HTTPS

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName =HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}

HttpRequest.IsSecureConnection Property (MSDN)

This entry was posted in ASP.NET and tagged , . Bookmark the permalink.

Comments are closed.