Tuesday, July 29, 2008

URL rewrite module

URL rewrite with simple REGEX:

It's really cool one and much faster when it go on live look into this file and if you don't understand please feel free to ask questions.


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Text;
using DAL;

namespace DAL
{
public class RewriteModule : IHttpModule
{

///
/// Init is required from the IHttpModule interface
///

///
public void Init(System.Web.HttpApplication Appl)
{
//make sure to wire up to BeginRequest
Appl.BeginRequest += new EventHandler(Rewrite_BeginRequest);

}

///
/// Dispose is required from the IHttpModule interface
///

public void Dispose()
{
//make sure you clean up after yourself
}

///
/// To handle the starting of the incoming request
///

///
///
public void Rewrite_BeginRequest(object sender, System.EventArgs args)
{
//Todo:
//Check the action field on the form to see that it postsback to the rewritten page



//Cast to a HttpApplication
HttpApplication Appl = (HttpApplication)sender;

//Check whether the page or a directory if its a directory then must end with '/'
string requestedURL = Appl.Request.RawUrl;
if (!requestedURL.Contains(".") && requestedURL.Substring(requestedURL.Length - 1) != "/")
{
//if (requestedURL.Substring(requestedURL.Length - 1) != "/")
//{
requestedURL = Appl.Request.Url.ToString() + "/";
//requestedURL = Appl.Request.Url.ToString() + "/index.htm";
//}
//else
//{
// requestedURL = Appl.Request.Url.ToString() + "index.htm";
//}
HttpResponse response = Appl.Response;
response.Clear();
response.Status = "301 moved permanently";
response.AddHeader("location", requestedURL);
response.End();
}

requestedURL = Appl.Server.UrlDecode(requestedURL);
if (!requestedURL.ToLower().Contains("admin/") && !requestedURL.ToLower().Contains("member/") && !requestedURL.ToLower().Contains("images/") && (requestedURL.ToLower().Contains(".htm") || requestedURL.ToLower().Contains(".aspx") || requestedURL.Substring(requestedURL.Length - 1) == "/"))
{
string[] LookFor = new string[] {
"~/(index\\.htm)?",//For ~/HomePage
"~/Health-Info/(index\\.htm)?",//For Health Info.aspx
"~/Health-Info/([A-Za-z0-9_% &+.-]*)\\.htm",//For Health Info/topic.htm
"~/Health-Info/([A-Za-z0-9_% &+.-]*)/([A-Za-z0-9_% &+.-]*)\\.htm",//For Health Info/topic/article.htm
"~/Search/([A-Za-z0-9_% &+.-]*)/([0-9]*)\\.htm",//For Health Info/topic.htm

"~/([A-Za-z0-9_\\^% &+.-]*)/(index\\.htm)?",//For ~/SectionName/index.htm section home page
"~/([A-Za-z0-9_\\^% &+.-]*)/([A-Za-z0-9_% &+.-]*)/([0-9]*\\.htm)?",//For ~/SectionName/Category/index.html
"~/([A-Za-z0-9_\\^% &+.-]*)/([A-Za-z0-9_% &+.-]*)/([A-Za-z0-9_% &+.-]*)-(Leaflet|Variant|Ingredients|Directions|DetailReview)\\.htm",//For ~/SectionName/Category/Product.html
"~/([A-Za-z0-9_\\^% &+.-]*)\\.htm",//For ~/SectionName/Category/Product.html
};
string[] SendTo = new string[]{
"~/Default.aspx",//Home Page
"~/HealthInfo.aspx?sec=Health Info",//Helath Info.aspx
"~/HealthInfoTopic.aspx?sec=Health Info&id=$1",//Helath Info.aspx
"~/HealthInfoArticle.aspx?sec=Health Info&id=$2",//Helath Info.aspx
"~/Search.aspx?k=$1&CPage=$2",//Search.aspx?k=&cpage=

"~/InternalHome.aspx?sec=$1",//Section Home Page
"~/Search.aspx?sec=$1&cid=$2&CPage=$3",//Page of product detail
"~/ProductDetail.aspx?sec=$1&cid=$2&pid=$3&page=$4",//Page of product detail
"~/$1.aspx"//Static Page
};
string SectionName = "";
for (int i = 0; i < LookFor.Length; i++)
{
// get the pattern to look for, and
// Resolve the Url (convert ~ into the appropriate directory)
string lookFor = "^" + ResolveUrl(Appl.Context.Request.ApplicationPath, LookFor[i]) + "$";

// Create a regex (note that IgnoreCase is set...)
Regex re = new Regex(lookFor, RegexOptions.IgnoreCase | RegexOptions.Compiled);

// See if a match is found
if (re.IsMatch(requestedURL))
{
if (i > 4)
{
SectionName = Appl.Server.UrlDecode(re.Replace(requestedURL, "$1"));
DataRow dr_Sec = PageBase.GetSectionFromXML(SectionName);
if (dr_Sec == null)
{
SectionName = "";
}
}
string sendToUrl = "";
// match found - do any replacement needed
if (i <= 4)
sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[i]));
else if (i > 4 && i < 8)
{
if (SectionName == "")
{
Appl.Response.Redirect("~/", true);
//sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[0]));
}
else
{
//int checkBrand = 0;
if (i == 5)
{
sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[i]));
}
else if (i == 6)
{
string CatNm = re.Replace(requestedURL, "$2");
DataRow dr_Cat = General.VerifyUrlParameter(CatNm, null, null);
if (dr_Cat != null)
{
sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[6]));
sendToUrl = sendToUrl.Replace(CatNm, dr_Cat["CategoryId"].ToString());
}
else
{
sendToUrl = FrontPageBase.AppPath + SectionName;
Appl.Response.Redirect(sendToUrl, true);
}
}
else if (i == 7)
{
string CatNm = re.Replace(requestedURL, "$2");
string ProdNm = re.Replace(requestedURL, "$3");
DataRow dr_Prod = General.VerifyUrlParameter(CatNm, ProdNm, null);
if (dr_Prod != null && dr_Prod["ProductId"].ToString()!="")
{
sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[7]));
sendToUrl = sendToUrl.Replace(CatNm, dr_Prod["CategoryId"].ToString());
sendToUrl = sendToUrl.Replace(ProdNm, dr_Prod["ProductId"].ToString());
}
else
{
sendToUrl = FrontPageBase.AppPath + SectionName + "/" + CatNm;
Appl.Response.Redirect(sendToUrl, true);
}
}

//if (HttpContext.Current.Server.UrlDecode(re.Replace(requestedURL, "$1")).ToLower() == "all brands")
// checkBrand = 1;
//else
// checkBrand = Brand.CheckBrandBusiness((HttpContext.Current.Server.UrlDecode(ReplaceCareteAnd(HttpContext.Current.Server.UrlDecode(re.Replace(requestedURL, "$1"))))));
//if (checkBrand == 1)
// sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[3]));
//else if (checkBrand == 2)
// sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[5]));
//else
// sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[6]));
}
}
//else if (i == 4)
//{
//int checkBrand = Brand.CheckBrandBusiness(HttpContext.Current.Server.UrlDecode(ReplaceCareteAnd(HttpContext.Current.Server.UrlDecode(re.Replace(requestedURL, "$1")))));
//if (checkBrand == 1)
// sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[3]));
//else if (checkBrand == 2)
// sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[4]));
//else
// sendToUrl = "404.aspx";
//}
//else if (i == 5)
//{
// sendToUrl = ResolveUrl(Appl.Context.Request.ApplicationPath, re.Replace(requestedURL, SendTo[7]));
//}
// Rewrite the URL
sendToUrl = ReplaceCareteAnd(sendToUrl);
Appl.Context.RewritePath(sendToUrl);
break; // exit the for loop
}
}
}
}

#region Resolve URL
///
/// Converts a URL into one that is usable on the requesting client.
///

/// Converts ~ to the requesting application path. Mimics the behavior of the
/// Control.ResolveUrl() method, which is often used by control developers.

/// The application path.
/// The URL, which might contain ~.
/// A resolved URL. If the input parameter url contains ~, it is replaced with the
/// value of the appPath parameter.

internal static string ResolveUrl(string appPath, string url)
{
if (url.Length == 0 || url[0] != '~')
return url; // there is no ~ in the first character position, just return the url
else
{
if (url.Length == 1)
return appPath; // there is just the ~ in the URL, return the appPath
if (url[1] == '/' || url[1] == '\\')
{
// url looks like ~/ or ~\
if (appPath.Length > 1)
return appPath + "/" + url.Substring(2);
else
return "/" + url.Substring(2);
}
else
{
// url looks like ~something
if (appPath.Length > 1)
return appPath + "/" + url.Substring(1);
else
return appPath + url.Substring(1);
}
}
}
#endregion

#region ReplaceCareteAnd
public static string ReplaceCareteAnd(string Val)
{
Val = Val.Replace("^", HttpContext.Current.Server.UrlEncode("&"));
return Val;
}
#endregion
}
}

No comments: