Jan 31 2007

ASP.NET and Ajax urlrewriting

Posted by admin under ASP.NET 2.0

You might have read this article on Url rewriting and while Scotts smk:form did work at that time - I couldn't get it to work after installing VS2005 SP1.

No idea why, but I decided it was time to look further. I have now started converting old apps to use Urlrewriting.net .

It might give you some trouble at first - it's a lot of web.config changes with httpmodules etc, however I think it would be worth it.

It works in all scenarios, such as master pages and ajax callbacks etc .

While the docs are pretty decent - it's often easiest to see other installations (so download the SampleWeb as well) so I decided to post my web.config for a games site I run:

First of all you of course need to reference the urlrewriting dll from your project. Then make these additions to web.config



<configSections>
    <section name="urlrewritingnet"
             requirePermission ="false"
             type="UrlRewritingNet.Configuration.UrlRewriteSection, UrlRewritingNet.UrlRewriter"  />
...
...
</configSections>

...


  <system.web>
    <httpModules>
      <add name="UrlRewriteModule"
           type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter" />
    </httpModules>
  </system.web>

...
...
  <urlrewritingnet
    rewriteOnlyVirtualUrls="true"
    contextItemsPrefix="QueryString"
    defaultPage = "default.aspx"
    defaultProvider="RegEx"
    xmlns="http://www.urlrewriting.net/schemas/config/2006/07" >
    <rewrites>
      <add name="category"  virtualUrl="(.*)/c_([0-9]*)/default.aspx"
           rewriteUrlParameter="ExcludeFromClientQueryString"
           destinationUrl="~/cat.aspx?c=$2"
           ignoreCase="true" />
      <add name="game"  virtualUrl="(.*)/i_([0-9]*)/default.aspx"
           rewriteUrlParameter="ExcludeFromClientQueryString"
           destinationUrl="~/play.aspx?i=$2"
           ignoreCase="true" />
    </rewrites>
    </urlrewritingnet>
...

As you can see I rewrite url like

/gamename/i_126/default.aspx to /play.aspx?i=126

likewise the category:

/categoryname/c_126/default.aspx to /cat.aspx?c=126

Things to look up for:

  • all rules must have unique names. I.e when you add a new I bet you copy an old one - make sure you change the "name" attribute.