Search code examples
c#-4.0asp.net-mvc-2maproute

How to use Routing in MVC for SEO Friendly URL


Generally we have following sample code in our global.asax file. So, my question is how we can have multiple MapRoute and how to use them ???

I want URL like:


http://domain/Home.aspx/Index/Cricket-Ball/12

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

I want something like this, but i don't understand how to use this routing so that i can get SEO Friendly URL:


        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default1",
                "{controller}/{action}/{productname}/{id}",
                new { controller = "Home", action = "Index", productname = UrlParameter.Optional, id = UrlParameter.Optional }
            );

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

Thanks in advance.


Solution

  • Since that's not a generic url but a concrete one (pointing to a product), you could use:

    public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoute(
                "Products",
                "home/index/{productname}/{id}",
                new { controller = "Home", action = "Index" }
            );
    
            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    

    So, everything not matching to "Products" route will go to "Default". Note that I didn't add the ".aspx" to the rout since I believe it's a mistake. If you actually want it, just add it to the route:

    routes.MapRoute(
                "Products",
                "home/index.aspx/{productname}/{id}",
                new { controller = "Home", action = "Index" }
            );
    

    Also, I would suggest to use a better url with:

    routes.MapRoute(
                "Products",
                "products/{productname}/{id}",
                new { controller = "Home", action = "Index" }
            );