Friday, April 16, 2010

URL Routing in ASP.NET 3.5 Webform

URL Routing decouples the URL from a physical file on the disk, we can define routing rules to specify what URL maps to what physical files. ASP.NET Routing is not only for MVC and is independent library so ASP.NET Routing can be used in a traditional ASP.NET web forms.

First, add a reference to System.Web.Routing and make sure that web.config has UrlRoutingModule HTTP Module registered in httpModules section.

then, we create this class,

CustomRouteHandler.cs
//------------------------------------------------------
public class CustomRouteHandler : IRouteHandler
{
public CustomRouteHandler(string virtualPath)
{
this.VirtualPath = virtualPath;
}

public string VirtualPath { get; private set; }

public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
foreach (var paramUrl in requestContext.RouteData.Values)
{
requestContext.HttpContext.Items[paramUrl.Key] = paramUrl.Value;
}
var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
}
//--------------------------------------------------
Then in Global.asax file and in Application_Start event, I will define my routing rules.

Global.asax
//----------------------------------------------
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}


private void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.Clear();

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");

routes.Add("IndexPage", new Route("index/{page-num}", new CustomRouteHandler("~/Home/index.aspx")));
routes.Add("Index", new Route("index", new CustomRouteHandler("~/Home/index.aspx")));
routes.Add("ContactUs", new Route("contactus", new CustomRouteHandler("~/Home/contactus.aspx")));

}

The Route Data will be stored in HttpContext.Item (cache per request)
You can get the Route Data from HttpContext.Current.Items["name"] on the page.

Cheers!

2 comments:

yns said...

routes.Add("IndexPage", new Route("index/{page-num}", new CustomRouteHandler("~/Home/index.aspx")));

can i add querystring to the original path

routes.Add("IndexPage", new Route("index/{id}", new CustomRouteHandler("~/Home/index.aspx?id={id}")));

or how can i do this ?

Saeed said...

you can not have that
new CustomRouteHandler("~/Home/index.aspx?id={id}"))); because the parameter of CustomRouteHandler should be a valid virtual path.
but you can have querystring, it has nothing to do with RouteData. with
new CustomRouteHandler("~/Home/index.aspx");
u can have a url like this: /home/index/4?tab=2
and get that queryString using Request.QueryString["tab"]in the page

Post a Comment