Sunday, April 5, 2020

Route Parameter Constraints In Asp.Net Razor Pages

In this article we will understand Route Parameter Constraints In Asp.Net Razor Pages by Sagar Jaybhay





Route Parameter Constraints





Route Constraints is a
mechanism where it filters out or restricts unwanted route parameters to
reaching out to PageModel methods.





To add route constraints we need to add constraints in route template data. For example, if we want our id only accepts numeric value then for this is below code.





@page "/employee/view/id:int"




Now we want to apply constraints with optional parameters then we need to use below syntax.





@page "/employee/view/id:int?"




Below is a list of the table this kind of constraints we can apply in the route template.





Constraint
Description

Example

alpha

Matches
uppercase or lowercase Latin alphabet characters (a-z, A-Z)

title:alpha

bool 1

Matches
a Boolean value.

isActive:bool

int 1

Matches
a 32-bit integer value.

id:int

datetime 1

Matches
a DateTime value.

startdate:datetime

decimal 1

Matches
a decimal value.

cost:decimal

double 1

Matches
a 64-bit floating-point value.

latitude:double

float 1

Matches
a 32-bit floating-point value.

x:float

long 1

Matches
a 64-bit integer value.

x:long

guid 1

Matches
a GUID value.

id:guid

length

Matches
a string with the specified length or within a specified range of lengths.

key:length(8) postcode:length(6,8)

min

Matches
an integer with a minimum value.

age:min(18)

max

Matches
an integer with a maximum value.

height:max(10)

minlength

Matches
a string with a minimum length.

title:minlength(2)

maxlength

Matches
a string with a maximum length.

postcode:maxlength(8)

range

Matches
an integer within a range of values.

month:range(1,12)

regex

Matches
a regular expression.

postcode:regex(^[A-Z]2\d\s?\d[A-Z]2$)




We can apply more than
one constraint at a time for this use below syntax.





For example, we want to Id whose minimum value is 1 and max value 100 can accept





@page "/employee/view/id:min(1):max(100)"




How to create Custom Constraints in Asp.Net Razor pages?





There is a five-step method to create Custom Constraints in Asp.net razor pages.





  • First, we required the inbuilt interface for creating a constraint and below is Interface for that.




public interface IRouteConstraint : IParameterPolicy

bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection);





  • The second is to create a class and implement this interface in our newly created class and your required logic in match method which returns true or false.




public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)

if(values[routeKey].ToString().Trim().Length!=0)

var regex = new Regex("^[a-zA-Z0-9]4$");
if (regex.IsMatch(values[routeKey].ToString()))
return true;

return false;





  • The now third step to add a custom constraint to our route template for this use below code.




@page "/employee/view/id:custom"




  • When we run our application we get an error which is shown below.









An unhandled exception occurred while processing the request.





InvalidOperationException: The constraint
reference 'custom' could not be resolved to a type. Register the constraint
type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'.





Microsoft.AspNetCore.Routing.DefaultParameterPolicyFactory.Create(RoutePatternParameterPart parameter, string inlineText)









  • To overcome this error we need to add this constraint in configureservice method using ConstraintMap method




public void ConfigureServices(IServiceCollection services)

services.AddRazorPages();
services.AddSingleton<IEmployeeRepos, DBRepository>();
services.Configure<RouteOptions>(option =>

option.LowercaseUrls = true;
option.LowercaseQueryStrings = true;
option.AppendTrailingSlash = true;
option.ConstraintMap.Add("custom", typeof(CustomConstraints.custom));
);









By doing this our application work perfectly fine but when we pass more than 4 character id it will give below output.









Using custom constraints it will not throw an error but it shows 404 not found.





Now we need to understand each parameter in the Match method.





bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection);




Name Explnation

httpContext

An object
that encapsulates information about the HTTP request.

route

he router
that this constraint belongs to.

routeKey

The name of
the parameter that is being checked.

values

A dictionary
that contains the parameters for the URL.

routeDirection

An object that indicates whether the constraint check is being
performed when an incoming request is being handled or when a URL is being
generated.













GitHub:- https://github.com/Sagar-Jaybhay/AspNerRazorPages






No comments:

Post a Comment