Friday, October 19, 2012

Doing the URL re-write in ASP.Net

So you want to re-write URLs in a ASP.NET application? Well here is one solution ....

Intelligencia.UrlRewriter (http://urlrewriter.net/)

Setup in your project is simple, just add the following to the Web.Config

<configSections>

<section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"/>.

<httpHandlers>

<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>.

.. then you add a section like that below:

<rewriter>

<rewrite url="~/Contracts/?(.*)" to="~/Contracts.aspx?ID=$1" />

i.e. When the user tries to access the URL: /Contracts/">http://<server>/Contracts/ this will be converted to the application as /Contracts.aspx/">http://<server>/Contracts.aspx/

But what about the “?(.*)” ? I hear you cry .. Well this is a Regular Expression that lets you parse the rest of the URL entered. For example “/contracts/ABC” will be converted to “/contracts.aspx?ID=ABC”. You can of course get all fancy and take out specific values for things so the URL becomes far more meaningful, but that I’ll leave up to you to Google on the web.

One good into blog is here: http://www.blogiversity.org/blogs/blogdayafternoon/archive/2008/12/18/url-rewriting-using-intelligencia-urlrewriter.aspx)

So what are the Problems?

1) Well the biggest issue you get is with Post backs.. When you do an ASP.NET postback it sometimes plays around with the “action=” URL for your form. As an example it takes the converted URL : contracts.aspx and sets the forms “Post” action to “contracts.aspx”. that’s fine until it gets back to the rewriter which converts this to “contracts.aspx?ID=.aspx” !! which won’t work.

To get around this issue you just have to put the following in the site.master code behind.

masterform.Action = Request.RawUrl;

In your Master Page you make sure the form name matches this;

<form ID="masterform" runat="server">

2) Another issue you might face is that the URL rewriting is order specific, i.e. once it finds a URL that matches that entered it will assume you’re calling that page. For example “/contactsForMyApplication/” you may want to go to the “/contactsForMyApplication.aspx” page, but it the appears *after* the “/Contracts/ rewrite entry you’ll find yourself hitting the “contracts.aspx” page by mistake.

To get around this you need to be careful of the ordering in the web.config and you can put an attribute (which I can’t remember) option in the <rewrite> node which stops further processing.