Route Constraints in ASP.NET MVC

Route Constraints in ASP.NET MVC Application

In this article, I am going to discuss how to define Route Constraints in ASP.NET MVC Applications with examples. Please read our previous article where we discussed how to create Custom Routes in ASP.NET MVC Application. As part of this article, we are going to discuss the following pointers which are related to ASP.NET MVC Route Constraints.

  1. What are Route Constraints in ASP.NET MVC Application?
  2. Creating Route Constraint to a Set of Specific Values in MVC Application.
  3. What is the difference between Routing and URL Rewriting?
  4. How is the routing table created in ASP.NET MVC?
What are Route Constraints in ASP.NET MVC Application?

The Route Constraint in ASP.NET MVC Routing allows us to apply a regular expression to a URL segment to restrict whether the route will match the request. In simple words, we can say that the Route constraint is a way to put some validation around the defined route. Suppose you have defined the following route in your application.

namespace FirstMVCDemo
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            
            routes.MapRoute(
                name: "Default", //Route Name
                url: "{controller}/{action}/{id}", //Route Pattern
                defaults: new
                {
                    controller = "Home", //Controller Name
                    action = "Index", //Action method Name
                    id = UrlParameter.Optional //Defaut value for above defined parameter
                }
            );
        }
    }
}

Now you want to restrict the incoming request URL with numeric id only. Now let’s see how we can do this with the help of regular expression in the ASP.NET MVC Application.

Restrict to numeric Id only

There is another overloaded version of the MapRoute extension method which takes constraints as a parameter. Using this parameter we can set a regular expression that will validate the incoming URL route parameters. In the below code, you can observe, we have passed constraints :new { id = @”\d+” } as the fourth parameter to the MapRoute extension method, and this regular expression will restrict the id parameter to be numeric only,

namespace FirstMVCDemo
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default", //Route Name
                url: "{controller}/{action}/{id}", //Route Pattern
                defaults: new
                {
                    controller = "Home", //Controller Name
                    action = "Index", //Action method Name
                    id = UrlParameter.Optional //Defaut value for above defined parameter
                },
                constraints :new { id = @"\d+" } //Restriction for id
            );
        }
    }
}

So now if you give a non-numeric value for the id parameter then that request will be handled by another route or if there are no matching routes then the “The resource could not be found” error will be thrown. So now for the above route, the routing engine will only consider the URLs which have only numeric id like http://dotnettutorials.com/Home/Index/10

Creating Route Constraint for Restricting Controller and Actions

Suppose you want to restrict the user for those URLs that have controller name with H prefix and action name should be only Details or About. Now let’s see how we can achieve this with the help of regular expression.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
             "Default", // Route name
             "{controller}/{action}/{id}", // Route Pattern
             new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
             new { controller = "^H.*", action = "^Details$|^About$" } //Restriction for controller and action
        );
    }
}

Now for this route, the routing engine will consider only those URLs which have controller name with H prefix, and action names should be only Details or Index.  such as http://dotnettutorials.net/Home/Indexhttp://dotnettutorials.net/Home/Details, and http://dotnettutorials.net/http:// dotnettutorials.net/Home else it will consider that URL is not matched with this route.

Now you may be a little bit confused about why it will consider the http://dotnettutorials.net/http:// dotnettutorials.net/Home URLs?

It will also consider both these since route constraint is checked after the provided default values for controller and action. In the above route default values for controller and action are Home and Index so these two URLs will also be matched. Like this, you can restrict the user according to your needs.

What is the difference between Routing and URL Rewriting?

Many developers compare Routing to URL rewriting since both look similar and can be used to make SEO-friendly URLs. The main differences between routing and URL rewriting are given below:

  1. URL rewriting is focused on mapping one URL (new URL) to another URL (old URL) while routing is focused on mapping a URL to a resource i.e. controller action method.
  2. URL rewriting rewrites your old URL to a new one while routing never rewrites your old URL to a new one but it maps to the original route.

In the next article, I am going to discuss Attribute Routing in ASP.NET MVC Application. Here, in this article, I try to explain the Route Constraints in the ASP.NET MVC Application with Example. I hope this Route constraint in the ASP.NET MVC article will help you with your needs.