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

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 ...

Workflow Foundation 4 - Part 3 - Data storage and management

This is my third post on WF4. First one was an introductory post on WF4 and in second one we focused on executing workflows. In the this post I am going to focus on the topic of data storage and management. Every business process or flow depends on data. When you think of data there are three elements to it as listed below - Variables - for storing data Arguments - for passing data Expressions - for manipulating data. Let us first look at the variables. Variables are storage locations for data. Variables are declared before using them just like in any other languages like C# or VB.Net. Variables are defined with a specific scope. When you create a variable in an activity the scope of the variable becomes that activity's scope. Variables can also have access modifiers like None, Mapped or ReadOnly. Let us look at an example where we will create two variables and assign a scope to them along with access modifiers. //Declare a sequence activitiy Sequence seqWf = new Sequence(); //de...

Introduction to Workflow Foundation 4 (WF4)

I finally decided to pick-up my blogging once more. Since I have been trying to learn Windows Workflow Foundation 4 (WF4) I thought I might as well start off with this topic. WF4 is a development framework that enables you to create a workflow and embed it in a .Net application. It is neither an executable application nor a language. It provides a set of tools for declaring a workflow, activities to create your logic and to define control flow and a runtime for executing the resulting application definition. It also provides services for persistence of state, tracking and bookmarking. You can create your workflow directly in code, in mark-up or in a combination of both. Workflow provide us with two major advantages - Creating unified application logic. Making application logic scalable. Workflow Authoring styles - Sequential Workflow executes a set of contained activities in a sequential manner. Workflow Foundation was introduced in the .Net 3.0 and updated in 3.5. In .net 4 it has bee...