Paul
Paul

Reputation: 680

c# MVC routing - multiple routes

I have a default c# mvc routes:

routes.MapRoute(

    "Default",

    "{controller}/{action}/{id}"

    new { controller = "Home", action = "Index", id = "Welcome" }

);

Now I will get urls like:

mysite.com/Home/Index/Page1
mysite.com/Home/Index/Page2
mysite.com/Home/Index/Page3
mysite.com/Account/Login
mysite.com/Account/Etc

But I would like to have the first set with a shorter url like:

mysite.com/Page1
mysite.com/Page2
mysite.com/Page3
mysite.com/Account/Login
mysite.com/Account/Etc

I expected the code to be really simple like:

routes.MapRoute(

    "Shorturl",

    "{id}",

    new { controller = "Home", action = "Index", id = "Welcome" } 

);

routes.MapRoute(

    "Default",

    "{controller}/{action}/{id}"

    new { controller = "Home", action = "Index", id = "Welcome" }

);

But that doesn't work. It will only take the first route and forget the second. How can you make your program take the first route when there is only one parameter (like mysite.com/Page1) and take the second route when you have multiple routes (like mysite.com/Account/Login) ?

Edit: I can do:

routes.MapRoute("Short", "short/{id}", new { controller = "Home", action = "Indx", id = "Page1" } );

But then I would have an ugly "short/" in the url. I can fix it with:

routes.MapRoute("Page1", "Page1", new { controller = "Home", action = "Index", id = "Page1" } );

But then I need to add each new page manually...

Upvotes: 6

Views: 4684

Answers (1)

Sitnam
Sitnam

Reputation: 164

You might want to try something like this.

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

        routes.MapRoute(
            "Short", // Route name
            "{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

make sure that you add this to the route before the default(or even remove the default if you want)

But the order in which these are added is important.

There was one bit of info missing, and that the Action within the controller.

public ActionResult Index(string id)
{
      ViewBag.Message = "Welcome to ASP.NET MVC!"+id;
      return View();
}

Hope this helps.

Regards.

Upvotes: 3

Related Questions