0% found this document useful (0 votes)
11 views9 pages

Custom Route Constraints in ASP.NET Core

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

Custom Route Constraints in ASP.NET Core

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Custom Routing in ASP.

NET Core MVC Application


 Custom Routing allows us to define our own routing patterns for our web
application, thereby giving us more control over how URLs are mapped to
controller actions.

 This can be useful when creating SEO-friendly URLs, handling specific


routing scenarios, or creating a more organized and structured URL
hierarchy.

Custom Route Constraints in [Link] Core MVC Web


Application
 Custom Route Constraints allow us to enforce specific rules on the routes at
the routing level, which can help to ensure that URLs match expected
formats, values, and conditions.

 These constraints can be used to validate parameters in the URL before the
request even reaches the controller action.

 Custom route constraints allow us to implement complex route validation


logic (such as being an integer, having a specific range of values, or
matching a regular expression) for the route parameters that cannot be
expressed with standard constraints like int, guid, minlength, etc.
How do you Create a Custom Route Constraint in [Link]
Core?
 To create a Custom Route Constraint in [Link] Core MVC,

 we must create a class that implements the IRouteConstraint interface.

 This interface has a single method called Match, and we need to implement
this Match method to define our custom constraint logic.

 This method contains the logic to check whether a particular URL parameter
meets a specific requirement and returns a boolean indicating whether the
constraint is met.

 If you go to the definition of the IRouteConstraint interface, you will see the
following.
 This method takes the following five parameters.

 HttpContext? httpContext: This parameter provides the context


of the current HTTP request. It includes all information about the
request, such as headers, cookies, and the request path.

 IRouter? route: The router that this constraint belongs to, i.e., the
URL.

 string routeKey: This is the name of the route parameter to which


you apply the constraint. For example, if your route is defined
as {controller}/{action}/{id:int}, and you have a constraint on the
id parameter, the routeKey would be “id”.

 RouteValueDictionary values: This dictionary contains all the


route values for the current request. This is where you retrieve
the value of the parameter that you need to validate. You can
access it using the routeKey.

 RouteDirection routeDirection: This parameter indicates whether


the routing is happening for an incoming request or a URL
generation. The values can
be [Link] or [Link]
ation. This is important because you might want to apply the
constraint differently depending on whether the URL is being
generated or processed in response to an incoming request.
Example to Understand Custom Route Constraint in [Link]
Core MVC

Step => 1 Create the Custom Route Constraint Class


i. We will create a Custom Route Constraint to validate the Alpha Numeric
String. That means if the incoming Route Data Contains both Alphabet and
Numeric, it will be considered a valid value; if it contains only alphabet or
only numeric, it will be considered an invalid value.

ii. For this, we don’t have any built-in constraint in [Link] Core, and to
achieve this in [Link] Core MVC Application, we need to create a Custom
Route Constraint.

iii. So, create a class file named [Link] within the Models
folder and copy and paste the following code.

iv. As you can see, the class implements the IRouteConstraint interface and
provides the implementation for the Match method.

v. As part of the Match method, we implemented one alphanumeric regex to


check the incoming request parameter and determine whether the route
parameter contains Alphabets (A-Z, a-z) and numeric (0-9). If it contains
both alphabet and numeric, it returns true; otherwise, it returns false.
Step => 2 Register the Custom Route Constraint
i. Before using the Custom Route Constraint, we need to register it with the
Routing System. This is typically done in the [Link] file.

ii. We need to register the Custom Route Constraint within


the ConstraintMap dictionary.

iii. The ConstraintMap is a dictionary that contains the list of built-in route
constraints.

iv. So, we have to add our Custom Route Constraint to this ConstraintMap
dictionary with the help of route options. We can register the Custom Route
Constraint service to the built-in dependency Injection container in two
ways. They are as follows:

Method 1: Configuring the Custom Route Constraint Service using the


AddRouting Method
[Link](options =>
{
[Link]("alphanumeric", typeof(AlphaNumericConstraint));
});
Method 2: Configuring the Custom Route Constraint Service using the
Configure Method
[Link]<RouteOptions>(routeOptions =>
{
[Link]("alphanumeric", typeof(AlphaNumericConstraint));
});

Step=> 3 Use the Custom Route Constraint in Route


Configuration:
i. Once you register the Custom Route Constraint, then you can use the
Custom Route Constraint in the Route Template. You have to use the “:”
separator between the route parameter and constraints.
ii. For example, you can use the alphanumeric (whatever name you
provided while registering the service) route constraint as follows:
[Link](
name: "CustomRoute",
pattern: "{controller}/{action}/{id:alphanumeric?}",
defaults: new { controller = "Home", action = "Index" }
);

Ad

 Note: You can use the Custom Route Constraint in both Convention-
Based and Attribute-Based Routing in [Link] Core Application.

 In the above code, we have specified the id parameter with Custom Route Constraint
alphanumeric and made this parameter optional.

 Now, you can access the Index and Details action method without
passing any route values.
 However, if you want to pass route values for the Details action method,
the value should be alphanumeric; otherwise, it will give a 404 Resource
Not Found Error.

Step 4: Implement Controller Actions


In your controller (e.g., StudentController), you can now define actions that utilize this route
configuration. For instance:

Summary

 Create the Constraint: Implement IRouteConstraint in a class that defines your


constraint logic.
 Register the Constraint: Add the custom constraint to the routing system using AddRouting
method in [Link].
 Use the Constraint: Apply the custom constraint to route parameters in route configuration
(MapControllerRoute).
 Implement Controller Actions: Define actions that correspond to the configured routes.

You might also like