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.

6 comments:

  1. Hi,

    I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of URL Routing in ASP.Net 3.5(IIS7) and it helped me a lot. Thanks for sharing with us. Check out this link too its also having nice post with wonderful explanation on URL Routing in ASP.Net 3.5(IIS7), for more details check this....

    http://mindstick.com/Articles/9992a0bc-90f5-4f04-823a-31f901b61643/?URL%20Routing%20in%20ASP.Net%203.5%28IIS7%29

    Thank you very much!

    ReplyDelete
  2. Thank you Pravesh for the URL it is a nice post.

    ReplyDelete
  3. how to do www.mysite.com/username in asp.net c# plase reply?

    ReplyDelete
    Replies
    1. @Sagar Bhogale,

      Try this if it helps.

      RouteTable.Routes.Add("Username", new Route("{UserName}", new SiteRouteHandler() { PageVirtualPath = "~/Username.aspx" }));

      Thanks,
      Maulik Dhorajia

      Delete
  4. Hi Maulik, I was trying to implement Url Rewriting as you have shown, however for some reason Context.Items["qparam.XX"]always turns to be null. Am I missing anything apart from what you have shown above.

    In my case, its like page Home.aspx resides directly under root. So I want:
    Home/{id}/{name} .. to be rewritten to Home.aspx?id={id}&name={name}

    Can you please help with this.

    ReplyDelete
    Replies
    1. Hello Jawed,

      I would suggest to check the case sensitive in the Route or the qparam.id. This might be one of the reason. I try and keep all the examples tried and tested.

      Thanks,
      Maulik Dhorajia

      Delete