Skip to main content

URL Rewriting

When I first ventured into this topic I thought this would be pretty straight forward but then being in software field I should have known better. Nothing is as simple as it sounds.

So here we go URL re-writing in ASP.Net. What URL re-writing means is that you intercept an incoming web request in your web application and then redirect the web request to a different web resource in your web application. Now this is not done simply using Response.Redirect or Server.Redirect.

There are many reasons why you would choose to do URL re-writing and the major
ones could be -


  • You want your urls to be search engine friendly.

  • Your website has undergone restructuring or you expect the folders to be moved
    arround later.

  • You want your urls to be user friendly (as in easier to remember).

Any web request when it enters the ASP.Net engine an HTTPContext object is created and assigned to it and then it goes through a series of HTTPModules finally hitting a HTTPHandler. The HTTPContext object provides a method called RewritePath(). This is the method that we can use to redirect the web request to a different resource. HTTPContext also give you the access to Request object which can be used to extract and analyse RawURL for generating
querystring information and currently requested resource.

Steps to implement URL rewriting -


  • Create a website in ASP.Net

  • Add a class (URLRewriter) and make it implement IHTTPModule interface.

  • Add an entry in the web config's HTTPModule section so that your module gets picked up

  • Add an eventhandler for BeginRequest event by using the HTTPContext object in
    the Init method.

  • In the BeginRequest event handler type cast the sender to HTTPApplication and
    extract the current context

  • Analyse the RawURL from the Request object of the current context to ascertain
    if rewrite is required

  • If yes then use the context objects RewritePath method to redirect to a
    different resource.

  • Insert a base tag with base address on your master page

You will need to do one last thing before you can say that your url rewriting is working fine. At this stage if you run your application and check the source of the html that is rendered on the browser you will notice that there is an action tag in the form element and it is not pointing to the rewritten path or the new path that you used to redirect from the HTTPModule. This poses a problem as it will hinder in your normal page post backs. So you need to modify the form tag rendered by removing the action tag. You can do this using different approaches.



  • You can create a control adaptor which you can attach to the html form tag using
    a browser file.

  • You can create a class that inherits from HTMLForm class and use it instead of
    the form tag in your page.

  • You can create a class that inherits from Page class, override its Render
    method and use it to inherit all your form's code behind classes from.

I have used the third approach here.

That is it. Thats all you need to know about URL rewriting.


HTTP Module Class


public class URLRewriter:IHttpModule
{
public void Dispose()
{
}



public void Init(HttpApplication context)
{
context.BeginRequest +=

new EventHandler(context_BeginRequest);
}


void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication httpapp = sender as HttpApplication;
if (httpapp != null)
{
HttpContext currcontext = httpapp.Context;
string rawURL = currcontext.Request.RawUrl;
//your url might be of the form -

http://mysite.com/modid/1/techid/5/productid/10/productdetail

//analyze rawURL to see if you need to redirect the request
//analyze rawURL to extract any parameter information
string strQS = //generate and store normal query string here
//rewrite the new path here
currcontext.RewritePath("~/" + targetpage + strQS);
}
}
}


HTTPModule entry in the web.config file

<configuration>
<system.web>
<httpModules>
<add name="URLRewriter"

type="<namspace_namehere>.URLRewriter" />
</httpModules>
</system.web>
</configuration>


Base tag in the master page.

<head id="Head1" runat="server">
<base href="http://www.yourwebsitename.com/" />
</head >

Page base class

public class PageBase:System.Web.UI.Page
{
protected override void

Render(System.Web.UI.HtmlTextWriter writer)
{
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
base.Render(hwriter);
hwriter.Flush();
string html = swriter.ToString();
hwriter.Dispose();
int spos = 0;
spos = html.IndexOf("action=\"");
if (spos > 0)
{
int epos = 0;
epos = html.IndexOf("\"", spos + 8) + 1;
html = html.Remove(spos, epos - spos);
}
writer.Write(html);
}
}



Inherit Form Class from your new Page Base class


public partial class _Default : PageBase
{ }

Comments

Popular posts from this blog

Health Framework - Apple vs Android

In the past few years we have seen mobile and its apps rise and shine transforming many industries in its wake. However, the growth in health and fitness category has been less spectacular at 49% compared to overall mobile app industry which grew at 115% in the year 2013 (source Flurry Analytics). A few years ago Microsoft and Google attempted to make inroads into the health and fitness sector by bringing web based products to store and maintain health and fitness information like MS HealthVault and Google Health with not so spectacular results. Next came innovations by Fitbit in the wearables sector for activity tracking, in 2011 and 2012 they introduced first wireless activity trackers to sync using Bluetooth. This was followed by the entry of Jawbone into health sector with its announcements of Up wristband and accompanying app. These have had better success resulting in many startups joining the wearables product bandwagon.  Late to the stage almos...

Notes on Castle MonoRail

  Sometime back I was doing a small POC on Castle MonoRail. So here are my quick notes on this. MonoRail is an MVC Framework from Castle inspired by ActionPack. MonoRail enforces separation of concerns with Controller handling application flow, models representing data and View taking care of the presentation logic. To work with MonoRail you need Castle Assemblies. It also utilizes nHibernate You can use Castle MonoRail Project Wizard or create the project manually. Project structure – Content Css Images Controllers HomeController.cs Models Views Home \ index.vm Layouts \ Default.vm ...

Quick notes on Git

  I have been away from writing anything for a long time and instead have been fooling around with other stuffs like just plain reading, growing mustache, trying to learn swimming, trying to learn to play acoustic guitar and trying my hands at photography. To be honest I have not given up on them yet but neither have I been able to hang on to them in a disciplined manner. So here I am back to my writing after a long gap. This time its going to be quick notes on Git . Git is a file repository. As opposed to other repositories like SVN Git thinks of its data more like a snapshot of a mini filesystem. All operations in Git are local. (Entire history of the project is stored locally in your working directory) Browsing project history. Viewing all changes to a file. Git uses Checksum to track repository items Everything in Git is check-summed It uses SHA-1 hash for generating check sum values All a...