In your Global.asax file
protected void Application_BeginRequest(object sender, EventArgs e)
{
string path = HttpContext.Current.Request.Url.AbsolutePath;
if (HttpContext.Current.Request.ServerVariables["HTTPS"] == "on")
{
if (SecurePath.IsSecure(path))
{
}
else
{
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("https://", "http://"));
return;
}
}
if (HttpContext.Current.Request.ServerVariables["HTTPS"] != "on")
{
if (SecurePath.IsSecure(path))
{
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("http://", "https://"));
}
}
}
Here is the definition for SecurePath Class
#region "SecurePath Class"
public class SecurePath
{
public static bool IsSecure(string path)
{
List<securepage> lstPages = new List<securepage>();
bool isSecure = false;
try
{
NameValueCollection sectionPages = (NameValueCollection)ConfigurationManager.GetSection("SecurePages");
foreach (string key in sectionPages)
{
if ((!string.IsNullOrEmpty(key)) && (!string.IsNullOrEmpty(sectionPages.Get(key))))
{
lstPages.Add(new SecurePage { PathType = sectionPages.Get(key), Path = key });
}
}
foreach (SecurePage page in lstPages)
{
switch (page.PathType.ToLower().Trim())
{
case "directory":
if (path.Contains(page.Path))
{
isSecure = true;
}
break;
case "page":
if (path.ToLower().Trim() == page.Path.ToLower().Trim())
{
isSecure = true;
}
break;
default:
isSecure = false;
break;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return isSecure;
}
}
#endregion
</securepage></securepage>
Definition for securePage class
#region "SecurePage Class"
public class SecurePage
{
string _path = "";
string _pathType = "";
public string Path
{
get { return this._path; }
set { this._path = value; }
}
public string PathType
{
get { return this._pathType; }
set { this._pathType = value; }
}
}
#endregion
And in your web.config file add SecurePages section
<SecurePages>
<add key="/Login.aspx" value="page" />
<add key="/WebResource.axd" value="page"/>
<add key="/ScriptResource.axd" value="page"/>
</SecurePages>
P.S. :-
I found this solution from someone on CP and used in my project. It works perfectly. Credit goes to the developer who implemented it.