Routing constraints let you restrict how the parameters in the route template are matched. It helps to filter out the input parameter and action method it can accept.
For example, if the URL Parameter is restricted to have int value, the route engine will match the controller action having integer value in the parameter or restrict it.
How Route Constraints are applied:
- Using constraint parameter in the MapControllerRoute at the application startup where the endpoints are defined; i.e. Inline Constraint
- Route attribute at the controller or action method
- endpoints.MapControllerRoute(
- name: "default",
- pattern: "controller=Home}/{action=Index}/{id:int?}");
When the route engine matches the incoming url, it invokes the routing constraint to the values in the url which match the pattern. In this case which is seperated by : in the above example restricts the value should be int or null.
Here's a quick example on how the routing constraints are defined and used.
Inline Constraint
Inline constraint are added after the URL parameter and sperated by : (colon) with the primitive type and also defined if the parameter can be nullable. Below code see – {id:int?}
- app.UseEndpoints(
- endpoints =>
- {
- endpoints.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id:int?}");
- }
- );
The int constraints checks if the parameter value sent is integer and allows you to execute the action method by passing the parameter value to the matching method.
The other way to define the same is to pass the default values and constraint parameter in the MapControllerRoute
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllerRoute(
- name: "default",
- pattern: " {controller}/{action}/{id?}", new {Controller = "Home", action="Index"}, new {id = new IntRouteConstraint()});
- }
- );
Constraints in route attribute

Roshan RathodPosted Oct 2, 2020, 6:25 AM
Nice........