refactor
refactor

Reputation: 15044

Routes in ASP.NET MVC 5

My requirement is I need to set multiple routes to same controller/action method.

If user enters url http://localhost:xxxx/home/index , it will target "index" action method of "home" controller.

I also want "http://localhost:xxxx/products" and "http://localhost:xxxx/categories" to point to "index" action method of "home" controller.

I was able to achive this by adding two routes "categories" and "products" as mentioned below , and it is working fine.

 routes.MapRoute(
      name: "categories",
      url: "categories",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  );

    routes.MapRoute(
      name: "products",
      url: "products",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  );


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

My question is , is there any way I combine those two routes "categories" and "products" in to one ?

Upvotes: 2

Views: 251

Answers (1)

Andrew Shepherd
Andrew Shepherd

Reputation: 45222

You can achieve this by adding a constraint to your route.

Make the entire path a parameter, and then assign a regular expression rule to match this parameter.

routes.MapRoute(
    name: "IndexMapper",
    url: "{alternateIndexName}",
    defaults: new { controller="Home", action="Index" },
    constraints: new { alternateIndexName="(categories)|(products)"}
);

https://msdn.microsoft.com/en-us/library/cc668201.aspx#Anchor_6

Upvotes: 2

Related Questions