Brains Coders

Brains Engineering Blog

Asp.Net Web Forms: Routing and friendly URLs

In order to enable URL rewriting and/or friendly URLs, you must create the RouteConfig class in the App_Start folder:

    public static class RouteConfig
    {
        public static string BaseUrl
        {
            get { return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/"); }
        }
        public static void RegisterRoutes()
        {
            // empty route collection
            RouteTable.Routes.Clear();
            RouteTable.Routes.Add(new Route("myCustomPageName", new PageRouteHandler("~/web/myPage.aspx")));
            RouteTable.Routes.Add(new Route("", new PageRouteHandler("~/web/Default.aspx")));
            RouteTable.Routes.EnableFriendlyUrls();
        }
        public static bool isValidRoute(string pageRouteName)
        {
            return !(pageRouteName.Contains("http") || pageRouteName.ToLower().Contains(".aspx") || pageRouteName.Contains("default.aspx") || pageRouteName == "" || pageRouteName.Length < 2);
        }

    }


in the BuildRoutes method, we can write the logic to build the routing table. So when the user will write "http://www.mysite.com/myCustomPageName" the request will be redirected to "http://www.mysite.com/web/myPage.aspx".


The command EnableFriendlyUrls() is used to quickly enable a simple URL rewriting by allowing request without the file extension and the parsing of segments, in example I can request the page above as "http://www.mysite.com/web/myPage"

For making this feature working, the package FriendlyURLs must be installed (it will create for you the above class)


EnableFriendlyUrls

with this feature enable you can browse the page simply typing: http://www.mysite.com/web/myPage

To pass additional parameters just add them after the page name separated by a /:

http://www.mysite.com/web/myPage/foo/bar


In the code behind of our web page we can retrieve such parameters by looping the segments:


        protected void Page_Load(object sender, EventArgs e)
        {
            IList<string> segments = Request.GetFriendlyUrlSegments();
            foreach(var segment in segments)
            {
                LblDebug.Text += segment + ";";
            }
        }

and the output will be:  foo;bar


MapPageRoute

The same result can be achived by using the MapPageRoute method of the RouteCollection object.

The difference with the EnableFriendlyUrls method is that we have to define manually all the possible routes, but we have more control on the whole process.


To define a route we have to use the following command that we can include in the RegisterRoute method of our RouteConfig class:


        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("",
                "Category/{action}/{categoryName}/{lang}",
                "~/web/page01.aspx",
                true,
                new RouteValueDictionary { { "categoryName", "food" }, { "action", "show" }, { "lang", "en-UK" } });
        }

By registering the above route, when the user will browse to http://www.mywebsite.com/category the request will be modified with the default value we have specified:

http://www.mywebsite.com/category/show/food/en-UK

and then forwarded to the page web/page01.aspx

here we can retrieve the parameters (segments) with the following code:

            string action = (Page.RouteData.Values["action"]).ToString();
            string catName = (Page.RouteData.Values["categoryName"]).ToString();
            string lang = (Page.RouteData.Values["lang"]).ToString();


Loading