ASP.Net 4.0 URL routing

ASP.Net provides very powerfull URL rewritting feature.

It starts with registering Routes in Application Start event of Global.asax file. I am using C# in following HTML sample.

Start with importing System.Web.Routing namespace.

<%@ Import Namespace="System.Web.Routing" %>

Next you have to add PageRoutes to RouteTable using MapPageRoute function.

void Application_Start(object sender, EventArgs e)
    {
RouteTable.Routes.MapPageRoute("Sitemap", "sitemap", "~/sitemap.aspx"); 
}

MapPageRoute have 5 overloads.

  1. MapPageRoute(String, String, String)
  2. MapPageRoute(String, String, String, Boolean)
  3. MapPageRoute(String, String, String, Boolean, RouteValueDictionary)
  4. MapPageRoute(String, String, String, Boolean, RouteValueDictionary, RouteValueDictionary)
  5. MapPageRoute(String, String, String, Boolean, RouteValueDictionary, RouteValueDictionary, RouteValueDictionary)

First overload will be suitable for most of routes, however if you need to set defaul route values or contraints than you can explore other overloads as well. Check this MSDN Page.

Routes work in a sequence, so first if url match first route pattern although it was supposed to 3rd or 4rth route it will go to first route.

Check the sample code below.

Sample Code
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>

<script RunAt="server">

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

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.Ignore("{resource}.axd/{*pathInfo}");
        
        //Direct URL
        routes.MapPageRoute("Sitemap", "sitemap", "~/sitemap.aspx");
        
        //RudraSofttech Content Related URL
        routes.MapPageRoute("BlogListPage", "blog/", "~/list.aspx");
        routes.MapPageRoute("BlogYearListPage", "blog/{year}", "~/list.aspx", false,
            new RouteValueDictionary { { "year", DateTime.Now.Year.ToString() } },
            new RouteValueDictionary { { "year", @"\d{4}" } });
        routes.MapPageRoute("BlogMonthListPage", "blog/{year}/{month}", "~/list.aspx");
        routes.MapPageRoute("BlogDayListPage", "blog/{year}/{month}/{day}", "~/list.aspx");
        //anyother blog url pattern should be given to article page
        routes.MapPageRoute("BlogArticleRoute", "blog/{*pagename}", "~/article.aspx");
        
        //Any Damn Thing Catch Here
        routes.MapPageRoute("DefaultPageRoute", string.Empty, "~/custompage.aspx");
        routes.MapPageRoute("CustomPageRoute", "{*pagename}", "~/custompage.aspx");
    }

</script>

Feel free to ask any question related to ASP.Net Routing in comments bellow.

Subscribe for our monthly newsletter for updated articles and useful code scripts.

Share It

comments powered by Disqus
Chat With Us Close
Leave Message