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 Application with examples. Please read our previous article where we discussed how to create Custom Routes in ASP.NET MVC Application with some examples. As part of this article, we are going to discuss the following pointers.

  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 say that 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 to do it with the help of regular expression.

Restrict to numeric id 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 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 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 to a Set of Specific Values in ASP.NET MVC Application

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 to do it 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 name should be only Details or Index.  such as http://dotnettutorials.net/Home/Index, http://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 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. But both approaches are very much different. The main difference between routing and URL rewriting is given below:

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.

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.

How is the routing table created in ASP.NET MVC?

When an MVC application first starts, the Application_Start() method in global.asax is called. This method calls the RegisterRoutes() method. The RegisterRoutes() method creates the routing table for the MVC application.

In the next article, I will discuss Attribute Routing in ASP.NET MVC Application. Here, in this article, I try to explain the Route Constraints in ASP.NET MVC Application step by step with a simple example. I hope this article will help you with your needs. 

Leave a Reply

Your email address will not be published. Required fields are marked *