Apart from Model validation, custom validation and other validations we have seen, the data can also be validated at the route level itself when any segment variables data is passed in the url.
Let’s assume that we have to restrict a certain URL pattern for those controllers whose name starts with “R”, we can specify below routes.
/APP_START/ROUTECONFIG.CS
// goes to the url, when the controller starts with R
routes.MapRoute("ConstrainRouteR",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "RoutingStuffs", action = "Index", id =
UrlParameter.Optional },
new { controller = "^R.*" });
Notice the 4th parameter in above code that is the constraint parameter to specify. This instructs that if the controller name starts with “R” then only this route is used to serve the request. (Note that default route mechanism doesn’t need to be removed).
http://localhost:63087/Home/CatchAll/155/something doesn’t work as the controller name doesn’t start with “R”.
ACTION METHOD IN BOTH CONTROLLER
(RoutingStuffsController.cs and HomeController.cs)
public ActionResult CatchAll(string id = null, string catchall = null) { return View(); }
Similarly, we can also restrict the action method of a specific controller by specifying below route config.
// goes to the url, when the controller starts with R and action is either Index or About routes.MapRoute("ConstrainRouteRA", "{controller}/{action}/{id}/{*catchall}", new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional }, new { controller = "^R.*", action = "^Index$|^About$" });
Restricting a request type either GET or POST.
// Constraining a route using HTTP method routes.MapRoute("ConstraintRouteHttp", "{controller}/{action}/{id}/{*catchall}", new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional }, new { controller = "RoutingStuffs", action = "Index|About", httpMethod = new HttpMethodConstraint("GET", "POST") });
Restricting a request whose controller starts with H, action method is either Index or About and Id segment value is in between 10 and 20.
// Range routes constraint // controller starts with H, action is either Index or About, request typen is GET and Id value is in between 10 and 20 routes.MapRoute("ConstraintRouteRange", "{controller}/{action}/{id}/{*catchall}", new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional }, new { controller = "^H.*", action = "Index|About", httpMethod = new HttpMethodConstraint("GET"), id = new RangeRouteConstraint(10, 20) });
In this case, we might need to comment the default route that comes with project template so that it doesn’t conflict with this.