Saturday, January 1, 2011

URL Rewrite Using ASP.net 3.5 or Over

The blog will explin how we can achieve url rewriting in ASP.net 3.5 or Over.

Step 1 : Create a helper class title "SiteRouteHandler.cs".


#region System
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Routing;
using System.Web.Compilation;
#endregion

namespace UrlRewrite
{
/// <summary>
/// Handler for routing
/// </summary>
public class SiteRouteHandler : IRouteHandler
{
#region Properties

/// <summary>
/// Page Virtual Path
/// </summary>
public string PageVirtualPath { get; set; }

#endregion

#region Implements IRouteHandler

/// <summary>
/// Gets the handler in return
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
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;
}

#endregion
}
}


Step 2 : In global.asax.cs file declare the routes you want to give to the pages with a particular pattern. Use the SiteRouteHandler.cs class for getting the params mentioned in the route pattern. The "{ID}", "{AspxPage}" and "{PageNumber}" are the dynamic values which can be used on our aspx page for manupulation. So if the link is "http://localhost/UrlReWrite/blog/123/This-is-a-blog.aspx/32". Than according to the pattern "123" is {ID}, "This-is-a-blog" is {AspxPage} and 32 is {PageNumber}. "~/Blog.aspx" is the actual page.


using System.Web.Routing;
protected void Application_Start(object sender, EventArgs e)
{
//Clears all route
RouteTable.Routes.Clear();
//Handles the route
RouteTable.Routes.Add("Blog", new Route("blog/{ID}/{AspxPage}.aspx/{PageNumber}", new SiteRouteHandler() { PageVirtualPath = "~/Blog.aspx" }));
}




Step 3 : Now on Blog.aspx we can use params to retrieve the data.


/// <summary>
/// The blog id from the query string
/// </summary>
private int BlogID
{
get
{
if (Context.Items["qparam.ID"] == null)
{
return 0;
}
return Convert.ToInt32(Context.Items["qparam.ID"]);
}
}

/// <summary>
/// The blog id from the query string
/// </summary>
private string AspxPage
{
get
{
if (Context.Items["qparam.AspxPage"] == null)
{
return string.Empty;
}
return Context.Items["qparam.AspxPage"].ToString();
}
}

/// <summary>
/// The Page Number
/// </summary>
private int PageNumber
{
get
{
if (Context.Items["qparam.PageNumber"] == null)
{
return 0;
}
return Convert.ToInt32(Context.Items["qparam.PageNumber"]);
}
}


Please let me know about your thoughts.