Route could still pick wrong controller

How can I explicitly tell my RouteLink to select only & only specific Route in my RegisterRoutes.  I have the following Route:

routes.MapRoute(
"ShopCategories",
"{ShopName}/{ShopId}",
new { controller = "Category", action = "ShopCategories" },
new { ShopId = @"d+" }
);

and in my View:

@Html.RouteLink("Mens Jacket"
"ShopCategories",
new
{
ShopId = "123",
ShopName = "shop-name"
}, null)

As you can see I spicified route  and controller name so url "localhost/shop-name/123" will call my Category controller.  However since  If I have another route like: 

routes.MapRoute(
"CategoryProducts",
"{CategoryName}/{CategoryId}",
new { controller = "Product", action = "CategoryProducts" },
new { CategoryId = @"d+" }
);

and have another url:

@Html.RouteLink("Blue Jacket",
"CategoryProducts",
new
{
CategoryId = "35",
CategoryName = "category-name"
}, null)

"localhost/category-name/35" will still call Category Controller instead of product controller bacause of order of my routes.  To me this is very unsafe and buggy and I have to keep reordering my routes and as the project grows it becomes nightmare! I explicitly
specify "RouteName" in my @Html.RouteLink and in routes specific Controllers are also specified, but it seems they are being completely ignored and wrong route/controller could invoke.

The question is how can I "lock" my @html.RouteLink or ActionLink to a spepicif route regardless of their order in Application_Start()?

Regards

Med

I believe the problem is not with RouteLink. The problem is with MVC is to find the router matching the url. Your end url is same for both the routes. Try differentiating the urls for these two routes. May be you can have like this

routes.MapRoute(
 "ShopCategories",
 "category/{ShopName}/{ShopId}",
 new { controller = "Category", action = "ShopCategories" },
 new { ShopId = @"d+" }
 );

routes.MapRoute(
 "CategoryProducts",
 "product/{CategoryName}/{CategoryId}",
 new { controller = "Product", action = "CategoryProducts" },
 new { CategoryId = @"d+" }
 );

I added a prefix of category and product to the urls.

Hi,

Thanks for reply. Thats what I have already done by making route unique by adding static value "category" to url, but I can only write: "http://localhost/category/blue-jacket" instead of more SEO friendly "http://localhost/mens-jacket/blue-jacket".

I don’t understand the point of having Route and controller names in overload and not using them to invoke correct route/controller. There should be more reliable way to invoke correct route other than relying on url pattern to find matching route.  Unless
there is a way.

Regards

Med

Leave a Reply