Reputation: 2093
My site requires routes that look something like this:
/products/product1/subcategory
/products/product1/subcategory2
/products/product2/subcagetory
etc..
I've set up my routes to this:
routes.MapRoute("Product1", "products/product1/{action}" ....
routes.MapRoute("Product2", "products/product2/{action}" ....
I do this in order to ensure that the menu items redirect to the correct view, which works great, but our tester picked up that users can interchange the URL which returns irregular results, for example:
/products/product1/subcategory-for-product2
/products/product2/subcategory-for-product1
Is there a way of blocking this from happening?
Upvotes: 1
Views: 125
Reputation: 13541
As this is routing logic, you could create a custom constraint that checks whether subcategory belongs to the product:
public class CategoryConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// code to validate subcategory
}
}
... and use this constraint in your route definitions.
The validation would check of the category belongs to the product and if not, don't match it so that the URL ends in an invalid request (resource not found).
With this approach, every invalid incoming route is handled as well as generation of outgoing links; which I think is cleaner that doing it in the controller.
Read more.
EDIT: just found this related question.
Upvotes: 1