Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

ASP.NET core custom route constraint

Suggested Videos
Part 9 - Query string parameters in core razor pages | Text | Slides
Part 10 - Route parameters in core razor pages | Text | Slides
Part 11 - Route constraints in core | Text | Slides

In this video we will discuss creating a custom route constraint in core.

We discussed built-in route constraints in our previous video. If these built-in route constraints do not meet your application requirements, you may create a custom route constraint.

Creating custom route constraint in core

To create a custom route constraint implement IRouteConstraint interface. This interface is in Microsoft.AspNetCore.Http namespace.

IRouteConstraint interface has just one method - Match() for which we have to provide implementation. This method returns true if the constraint is satisfied, otherwise false.

public interface IRouteConstraint : IParameterPolicy
            bool Match(HttpContext httpContext, IRouter route, string routeKey, 
                       RouteValueDictionary values, RouteDirection routeDirection);

IRouteConstraint Match() method parameters

Parameter Description
httpContext Contains information about the HTTP request
route The router that this constraint belongs to
routeKey Contains the name of the route parameter
values A dictionary that contains the route parameter values
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

Custom route constraint example

Let's say in our project we only want to allow even numbers as valid Employee ID values. We can't use any of the built-in route constraints to enforce this. One way to achieve this is, by creating a custom route constraint.

The following custom EvenConstraint returns true if the employee id value is even otherwise false.

public class EvenConstraint : IRouteConstraint
    public bool Match(HttpContext httpContext, IRouter route, string routeKey,
        RouteValueDictionary values, RouteDirection routeDirection)
        int id;

        if (Int32.TryParse(values["id"].ToString(), out id))
            if (id % 2 == 0)
                return true;

        return false;

Register custom constraint

To use the custom route constraint, it must be registered with our application's ConstraintMap dictionary. We do this in the ConfigureServices() method of the Startup class.

public void ConfigureServices(IServiceCollection services)
    services.Configure<RouteOptions>(options =>
        options.ConstraintMap.Add("even", typeof(EvenConstraint));

Using custom route constraint

Once a custom route constraint is registered, it can then be used just like any built-in route constraint.

@page "/employees/view/{id:even}" core razor pages tutorial

No comments:

Post a Comment

It would be great if you can help share these free resources