Friday, 4 May 2012

URL Rewriting in ASP.NET 2.0

In order to rewrite the url called www.domain.com/myfolder/items.aspx?Item_ID=1 to
www.domain.com/items/1 or www.domain.com/items/1.html or www.domain.com/items/1.aspx follow the steps


1. Create an xml file under root directory named as Rule.xml and write this code


<?xml version="1.0" encoding="utf-8" ?>
<urlrewrites>
  <rule>
    <url>item/(.*)</url>
    <rewrite>myfolder/items.aspx?Item_ID=$1</rewrite>
  </rule>
  <rule>
    <url>item/(.*)\.html</url>
    <rewrite>myfolder/items.aspx?Item_ID=$1</rewrite>
  </rule>
  <rule>
    <url>item/(.*)\.aspx</url>
    <rewrite>myfolder/items.aspx?Item_ID=$1</rewrite>
  </rule>
  <rule>
    <url>Products/Cart/(.*)\.aspx</url>
    <rewrite>Cart.aspx?ID=$1</rewrite>
  </rule>
</urlrewrites>


2. Add the below content in the Global.asax file


void Application_BeginRequest(Object sender, EventArgs e)
{
    string sPath = Context.Request.Path;//To overcome Postback issues, stored the real URL.
    Context.Items["VirtualURL"] = sPath;
    Regex oReg;
    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
    xmlDoc.Load(Server.MapPath("~/Rule.xml"));
    foreach (System.Xml.XmlNode oNode in xmlDoc.DocumentElement.SelectNodes("rule"))
    {
        oReg = new Regex(oNode.SelectSingleNode("url/text()").Value);
        Match oMatch = oReg.Match(sPath); if (oMatch.Success)
        {
            sPath = oReg.Replace(sPath, oNode.SelectSingleNode("rewrite/text()").Value); break;
        }
    }
    Context.RewritePath(sPath);
}

3. Create a class file named as Form.cs and paste this code


using System;
using System.Web.UI;
using System.Web;

public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter
{
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        base.Render(new RewriteFormHtmlTextWriter(writer));
    }
}

public class RewriteFormHtmlTextWriter : HtmlTextWriter
{

    public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
        : base(writer)
    {
        this.InnerWriter = writer.InnerWriter;
    }

    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)
        : base(writer)
    {
        base.InnerWriter = writer;
    }

    public override void WriteAttribute(string name, string value, bool fEncode)
    {
        // If the attribute we are writing is the "action" attribute, and we are not on a sub-control, 
        // then replace the value to write with the raw URL of the request - which ensures that we'll 
        // preserve the PathInfo value on postback scenarios 
        if ((name == "action"))
        {
            HttpContext Context = default(HttpContext);
            Context = HttpContext.Current;
            if (Context.Items["ActionAlreadyWritten"] == null)
            {
                // Because we are using the UrlRewriting.net HttpModule, we will use the 
                // Request.RawUrl property within ASP.NET to retrieve the origional URL 
                // before it was re-written. You'll want to change the line of code below 
                // if you use a different URL rewriting implementation. 
                value = Context.Request.RawUrl;
                // Indicate that we've already rewritten the 
's action attribute to prevent 
                // us from rewriting a sub-control under the control 
                Context.Items["ActionAlreadyWritten"] = true;
            }
        }
        base.WriteAttribute(name, value, fEncode);
    }
}


4. Write this line of code in every page which you want mask the url

protected override void Render(HtmlTextWriter writer)
{
    if (HttpContext.Current.Items["VirtualURL"] != null)
    {
        string sVirURL = HttpContext.Current.Items["VirtualURL"].ToString();
        RewriteFormHtmlTextWriter oWriter = new RewriteFormHtmlTextWriter(writer);//, sVirURL);
        base.Render(oWriter);
    }
}

5. To use this <a href="item/1">Mouse</a>




6. In items.aspx use like this


if (!IsPostBack)
   if (Request.QueryString["Item_ID"] != null)
 string id = Request.QueryString["Item_ID"].ToString();



Tags: URL Rewriting in ASP.NET 2.0,URL Rewriting with ASP.NET 2.0,url rewriting in asp.net,url rewriting, asp.net url rewriting example, url rewriting sample project,url rewriting in asp.net sample code

No comments:

Post a Comment

Parsing JSON w/ @ symbol in it

To read the json response like bellow @ concatenated with attribute                             '{ "@id": 1001, "@name&q...