Updated on Kisan Patel
This tutorial will show you how to validate the data passed in url at the routing level in ASP.NET MVC.
We can do validation at the route level itself when any segment variables data is passed in the url.
Let’s take example about we have to restrict a certain URL for controllers whose name starts with “K”, we can specify below routes…
Do this changes in RouteConfig.cs
// goes to the url, when the controller starts with K routes.MapRoute( name: "Default", "{controller}/{action}/{id}/{*catchall}", new { controller = "KHome", action = "Index", id = UrlParameter.Optional }, new { controller = "^K.*" });
This instructs that if controller name starts with “K” then this route can used to serve the request.
So that
– http://localhost:63087/KHome/CatchAll/155/something –> url works provided we have Catch All method in the RoutingStuffs controller.
– http://localhost:63087/Home/CatchAll/155/something –> doesn’t work as the controller name doesn’t start with “K”.
Similarly, we can also restrict the action method of a specific controller by specifying below route config.
routes.MapRoute("ConstrainRouteRA","{controller}/{action}/{id}/{*catchall}", new { controller = "KHome", action = "Index", id = UrlParameter.Optional }, new { controller = "^K.*", action = "^Index$|^About$" });
Restricting a request type either GET or POST.
routes.MapRoute("ConstraintRouteHttp", "{controller}/{action}/{id}/{*catchall}", new { controller = "KHome", action = "Index", id = UrlParameter.Optional }, new { controller = "KHome", 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.
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.
– http://localhost:63087/Home/Index/155 doesn’t work as Id segment value is 155 not between 10 and 20.
– http://localhost:63087/Home/Index/15 work as the Id segment value is in between 10 and 20