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.Add(new Route("myCustomPageName", new PageRouteHandler("~/web/myPage.aspx")));
            RouteTable.Routes.Add(new Route("", new PageRouteHandler("~/web/Default.aspx")));
        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 "" the request will be redirected to "".

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 ""

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


with this feature enable you can browse the page simply typing:

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

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


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)
                new RouteValueDictionary { { "categoryName", "food" }, { "action", "show" }, { "lang", "en-UK" } });

By registering the above route, when the user will browse to the request will be modified with the default value we have specified:

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();