How do I define a catch-all route for an ASP.NET MVC site?
-
03-07-2019 - |
Question
I have a news site with articles tagged in categories.
My Controller is called "Category" and this URL:
http://mysite.com/Category/Sport
passes Sport
to action Index
in controller Category
.
I want to allow the following URLs:
http://mysite.com/Sport/Hockey
http://mysite.com/Sport/Football
http://mysite.com/Science/Evolution
Which passes all category information to action Index
in controller Category
.
How do I create a catch-all route that handles all these and shuttles them to category?
Solution
There's a pretty good response to my question along these lines here.
OTHER TIPS
You can do it like this:
routes.MapRoute("Default", "{category}/{subcategory}",
new { controller = "CategoryController", action = "Display", id = "" }
);
and then in your controller:
public class CategoryController : Controller
{
public ActionResult Display(string category, string subcategory)
{
// do something here.
}
}
Do not that any the route above will be used for ALL routes (you can't have a About page etc unless you specify explicit routes before the above one).
You could however include a custom constraint to limit the route to only existing categories. Something like:
public class OnlyExistingCategoriesConstraint : IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
var category = route.DataTokens["category"];
//TODO: Look it up in your database etc
// fake that the category exists
return true;
}
}
Which you use in your route like this:
routes.MapRoute("Default",
"{category}/{subcategory}",
new { controller = "CategoryController", action = "Display", id = "" },
new { categoryExists = new OnlyExistingCategoriesConstraint() }
);
In that way it won't interfere with your other defined routes.