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.