Wednesday, September 23, 2009

URL Rewriting with ASP.NET 3.5 using System.Web.Routing.UrlRoutingModule

In asp.net 2.0 we used Context.RewritePath() or other URL rewrite modules. With asp.net 3.5 its easy to do. I did it for my blog for better SEO.

      • Add reference to system.Web.Routing
        Add System.Web.Routing.UrlRoutingModule http module to web.config
        Implement an IRouteHandler
        Registering routes in global.asax

I am going to rewrite blogs/Posts/{BlogPostID}/{*BlogPostTitle}

I implemented a generic IRouteHandler , it will copy url parameters( eg: BlogPostID,BlogPostTitle ) to http context item collection, so i can URL rewrite any page , without modifying IRouteHandler implementation.



using System;
using System.Web;
using System.Web.Routing;
using System.Web.Compilation;
using System.Web.UI;
public class SiteRouteHandler : IRouteHandler
{
//30 june 2009 Priyan R

public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
Page page;
page = BuildManager.CreateInstanceFromVirtualPath(PageVirtualPath, typeof(Page)) as Page;
foreach (var item in requestContext.RouteData.Values)
{
HttpContext.Current.Items["qparam." + item.Key] = item.Value;
}
return page;
}
public string PageVirtualPath { get; set; }
}

In global.asax added


       

routes.Add(
"BlogPost",
new Route("Blogs/Posts/{BlogPostID}/{*BlogPostTitle}",
new SiteRouteHandler() { PageVirtualPath = "~/Blogs/Details.aspx" })
);


So in Details.aspx I can read the parameters



Context.Items["qparam.BlogPostID"].ToString()
Context.Items["qparam.BlogPostTitle"].ToString()

Check the code.


Download Code

2 comments:

ashish said...

Hello,
When i write
routes.Add("customers/howitworks",
new Route("how-it-works",
new SiteRouteHandler() { PageVirtualPath = "~/howitworks.aspx" })
It does not on my site but when i write

routes.Add("howitworks",
new Route("customers/how-it-works.aspx",
new SiteRouteHandler() { PageVirtualPath = "~/howitworks.aspx" })

its work , is it necessary to ad extension?
How can i resolve that?
also it is not working with virtual directory.
BTW your code helps me a lot.
please help me to get out of the above problems.
Thanks

Priyan R said...

sorry for being late.. You need iis 7 integrated pipeline or iis 6 with .net 4 for extensionless urls.. please check the current web.config i made some changes