Cris
Cris

Reputation: 12194

ASPNET MVC Routing issue

I need to add a http://mysite/categoryname route, so i added

routes.MapRoute(
     "Categories",
     "{CategoryName}",
     new { controller = "News", action = "Category", CategoryName = "" },
     new string[] { "MyProj.Controllers" }
        );

The problem is that if i add it before

routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "News", action = "Index", id = UrlParameter.Optional }, 
     new string[] { "MyProj.Controllers" }
        );

Home page goes in error because it enters in Categories route; if i add Categories route in last position it is never entered and http://mysite/category_name gives me 404.

What am i doing wrong?

Upvotes: 2

Views: 386

Answers (2)

Chris Moschini
Chris Moschini

Reputation: 37957

No matter how you do this, as you add Categories, you will obviously run the risk of stepping on other pages in the site - so for example if you have a section of your site named /account and then someone creates a category named, "account," what's supposed to happen?

That said, there is a simpler answer than writing your own Routing class. You can use a Regex in the Category Route, and make it the first rule. For example, if the only 2 categories on the site were jackets and sweaters:

routes.MapRoute(
    "Categories",
    "{CategoryName}",
    new { controller = "News", action = "Category" },
    new { CategoryName = "(jackets|sweaters)" }
);

The final argument is a RouteConstraint based in Regex, and so the route will defer to routes included after it if the path is neither /jackets or /sweaters.

Obviously you want to be more robust than that, so you can create a method that builds the Regex at app startup:

routes.MapRoute(
    "Categories",
    "{CategoryName}",
    new { controller = "News", action = "Category" },
    new { CategoryName = "(" + String.Join("|", categories) + ")" }
);

categories here would need to be something you provide - some array or database feed of the category names in your app.

Upvotes: 1

Keith
Keith

Reputation: 5381

You have a few options here:

Change your news category route to include a hard path:

routes.MapRoute(
     "Categories",
     "category/{CategoryName}",
     new { controller = "News", action = "Category", CategoryName = "" },
     new string[] { "MyProj.Controllers" }
        );

Change your default route to include a hard path:

routes.MapRoute(
     "Default", // Route name
     "site/{controller}/{action}/{id}", // URL with parameters
     new { controller = "News", action = "Index", id = UrlParameter.Optional }, 
     new string[] { "MyProj.Controllers" }
     );

Roll your own custom routing class

See http://hanssens.org/post/ASPNET-MVC-Subdomain-Routing.aspx for an unrelated example.

Upvotes: 5

Related Questions