Incomplete Leo

Something from my heart

ASP.NET 2.0 and Url Rewrite – Simple

Simple approach :

A new feature in ASP.NET 2.0 is it’s built-in url rewriting support. When I looked into this new feature i found out it lacked regular expressions support, which is really the point of an Url Mapper. ScottGlu at his blog, explains the reason why the ASP.NET team didn’t implement this featur, basically because they realized that a full featured version would want to take advantage of the next IIS 7.0 new features, specially the support for all content-types (images and directories).

Anyway, it’s really simple to implement a Url Rewriting Module with Regex support in ASP.NET. I wrote a quick and simple HttpModule for this. The whole magic is done within a few lines within the HttpModule :

public void Rewrite_BeginRequest(object sender, System.EventArgs args) {

     string strPath = HttpContext.Current.Request.Url.AbsolutePath;

     UrlRedirection oPR = new UrlRedirection();

     string strURL = strPath;

     string strRewrite = oPR.GetMatchingRewrite(strPath);

     if (!String.IsNullOrEmpty(strRewrite)) {

          strURL = strRewrite;

     } else {

          strURL = strPath;


     HttpContext.Current.RewritePath("~" + strURL);

The code is self explanatory. When a request that is processed by

the ASP.NET engine, the module checks an XML for a regex match. I've

seen many Url Rewriting engines that uses Web.config to store the

matching rules but i prefer using an additional XML file. The rewriting

rules file look like the following:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>


     <rule name="Category Page">




     <rule name="Item Page">





The rule matching routine, wich is implemented in the GetMatchingRewrite() method is quite simple and lightweighted:

public string GetMatchingRewrite(string URL)  {
     string strRtrn = "";

     System.Text.RegularExpressions.Regex oReg;

     foreach (RedirectRule oRule in Rules) {

          Reg = new Regex(oRule.URL);
          Match oMatch = oReg.Match(URL);

          if (oMatch.Success)  {
               strRtrn = oReg.Replace(URL, oRule.Rewrite);

     return strRtrn;

 Sample here


Tháng Một 19, 2007 - Posted by | ASP.NET 2.0 Related

Không có bình luận

Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập: Logo

Bạn đang bình luận bằng tài khoản Đăng xuất /  Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất /  Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất /  Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất /  Thay đổi )


Connecting to %s

%d bloggers like this: