Work with URL Routing in Asp.Net

Leave a Comment

To register a route, you have to add a new RouteValueDictionary to the Routes property of the RouteTable class from the System.Web.Routing namespace. Typically, you can do that in global.asax or, if you prefer, in an HttpModule.

using (RouteTable.Routes.GetWriteLock())
RouteTable.Routes.Add("ArticleRoute",
new Route("articles/{id}/{description}",
new PageRouteHandler("~/Articles.aspx")));

In this listing, a new route was registered for a path that contains articles/, text that represents the ID, and free text that represents the clean URL. You can also use a similar URL without specifying the ID.

Now, you can modify the RouteHandler to manage additional details about the request. The new PageRouteHandler class hides some of the details to increase usability. In fact, you can simply retrieve the route parameter by accessing the new RouteData property on Page. The following listing shows you how to access the parameters in your pages.
protected int Id { get; set; }
protected string Description { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Id = Convert.ToInt32(Page.RouteData.Values["id"]);
Description = Page.RouteData.Values["description"] as string;
}

You can access parameters easily in typical scenarios where you need to pass simple values. If you need to specify different parameters (like an ID and a page number), but the last one is not mandatory, you can do one of the following things:

  • Define a default value for a parameter and register it with the route (using this method involves overloading
  • Define multiple routes and check for null parameters in the page


Registering a route with advanced parameters
Route articlesWithPageRoute =
new Route("articles/{id}/{description}/page{page}",
new PageRouteHandler("~/Articles.aspx"));
articlesWithPageRoute.Constraints = new RouteValueDictionary {
{ "id", @"\d{1,5}" },
{ "page", @"\d{1,5}" }
};
RouteTable.Routes.Add("ArticleRoutePaged", articlesWithPageRoute);

0 comments:

Post a Comment