Tuesday, March 2, 2010

Redirect from Http to Https in ASP.NET

Hello frnds,
In my one project, there is a requirement for redirect some page from HTTP to HTTPS.
So find one great article that will help me. So here I post the link of that article and code of how its work.

http://www.xdevsoftware.com/blog/post/Redirect-from-Http-to-Https-in-ASPNET.aspx

Code:-
-------------------------------------------------------
Class File Name: SecurePages.cs
-------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Collections.Specialized;
#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; }
}
}
#region "SecurePath Class"
public class SecurePath
{

public static bool IsSecure(string path)
{
List lstPages = new List();

bool isSecure = false;

try
{
//Fill the list of pages defined in web.config
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 });
}
}

//loop through the list to match the path with the value in the list item
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

#endregion


/* Add New custom section in web.config */

<configuration>
<configSections>
<section name="SecurePages" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<SecurePages>
<add key="/admin" value="directory" />
<add key="/WebForm2.aspx" value="page" />
<add key="/WebForm1.aspx" value="page" />
<add key="/myDir/myDirSec" value="directory" />
</SecurePages>
</configuration>

No comments: