Friday, March 6, 2009

URL Rewriting in the IIS 6

[gallery link="file"]

Follow the below mention steps for URL Rewriting in the IIS.

1) Open Properties of the Virtual Directory  from IIS.

2) Click on “Configuration”, from Virtual Directory Tab.

3) Click on “Add” from Mapping Tab.

4) Add the following path,

a. “X:WINDOWSMicrosoft.NETFrameworkv2.0.50727aspnet_isapi.dll”  in Executable.  (X is the Windows Drive. i.e. where the framework is installed”)

b. Type “.*” in Extension.

c. Uncheck the Option “Check that file Exist”.

Add the following code in Global.asax file

string[] arrPath;
string strPath = string.Empty;
string strUrl = string.Empty;
string strQS = string.Empty;
string strQrystr = string.Empty;

string strLocal = ConfigurationManager.AppSettings["Local"];

protected void Application_BeginRequest(object sender, EventArgs e)
{
string str1 = "UrlRequest";
string str2 = str1;

strQrystr = string.Empty;
strUrl = string.Empty;
setPath();

if (strPath.IndexOf(".") > 0)
{
return;
}
try
{
// ### Start - If main page(like http://localhost/websiteName/) then exit sub
if (strPath == "" || strPath == "/")
{
HttpContext.Current.RewritePath(strLocal + "/Default.aspx", "", "");
return;
}

strQS = Request.QueryString.ToString();

if (System.IO.File.Exists(Server.MapPath("~/" + arrPath[1] + ".aspx")))
{
strUrl = ConfigurationManager.AppSettings["Local"] + "/" + arrPath[1] + ".aspx";

if (arrPath.Length > 0)
{
for (int i = 0; i < arrPath.Length; i++)
{
if (arrPath[i] != null && arrPath[i] != "")
{
strQrystr = strQrystr + "q" + i + "=" + arrPath[i] + "&";
}
}
}
if (strQrystr.Length > 0)
{
strQrystr = strQrystr.Substring(0, strQrystr.Length - 1);
}
}
else
{
Response.Redirect(strLocal + "/Default.aspx");
}

//### Start - Actual Url Rewrite

if (strQS == "")
HttpContext.Current.RewritePath(strUrl, "", strQrystr + strQS);
else
{
if (strQrystr != "")
{
HttpContext.Current.RewritePath(strUrl, "", strQrystr + "&" + strQS);
}
else
{
HttpContext.Current.RewritePath(strUrl, "", strQS);
}
}
}
catch (IndexOutOfRangeException ex)
{
ex.Message.ToString();

}
catch (Exception ex)
{
ex.Message.ToString();
}
}
private void setPath()
{
strPath = HttpContext.Current.Request.Path.ToString().ToLower();

if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().IndexOf("localhost") != -1 || strLocal != "")
{
strPath = strPath.Replace(strLocal.ToLower() + "/", "");
}
else
{
strPath = strPath.Substring(1);
}
arrPath = strPath.Split('/');
}

Add following lines in web.config

<add key="Local" value="/VirtualdirectoryName"/>

No comments:

Post a Comment