Create Custom Route Constraints in Asp.Net MVC with Example

Here we will learn what is routing in asp.net mvc and how to create custom route constraints in asp.net mvc with example. Generally, in asp.net mvc routing module is responsible for mapping browser incoming requests to particular mvc controller actions.

 

Before moving to asp.net mvc routing, let’s look at asp.net webforms URL to know how it was mapped. Let's take a sample URL like http://localhost:2157/UserDetails/Admin.aspx/EmpId=10.This URL will tell that there is a UserDetails folder on the server, and inside that, we have a page with the name Admin.aspx, and it is accepting EmpID=10 as a Query string. It's difficult to remember this URL. In Asp.net Webforms, we directly map User requests to Physical files on Server.

 

After understanding Asp.net Webforms URL now, let’s check a similar URL in asp.net mvc http://localhost:1045/UserDetails/Admin/10 this URL is easy to understand, and it tells that there is a controller with the name UserDetails. It has an action method with the name Admin, and it has an optional parameter 10. According to this, we are going to retrieve records from the Database. In asp.net mvc, we will not map user requests directly to physical files first map to the controller, and then to Action Method inside that controller, and it returns a View().

How Asp.Net MVC URL Routing will Work?

Depending upon the URL request by user UrlRoutingModule find URL in the Route table for creating RouteData object. If UrlRouting Module finds a correct match, it goes to create RequestContext then forwards the request to the appropriate MVCHandler once the request received respective MVCHandler invokes execute method on Controller.

 

The Execute() method gets Action from the RouteData based on the requested URL. The MVC Controller will call Controller Action Invoker, which creates a list of parameters coming with URL. This parameter list will be passed to the Controller Action method. It calls the Invoke Action method to execute the action. Finally, send a response to the browser.

Understand How to declare Default Route

The routing file is stored in the App_Start folder of our project with the name RouteConfig.cs. In this file, we can configure our Route.

 

Default routing file in asp.net mvc application

 

The Basic Route which is available whenever we create asp.net mvc application. In our application, there is an App_Start folder inside that we can find RouteConfig.cs. This is the default route provided by the MVC application, and our default MVC RouteConfig Class will contain code like as shown below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace Tutorial3

{

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

}

}

}

Properties of Route

To create routes, we need to provide name, URL, object defaults parameters

 

Routes: A collection of routes for the application.

 

Name: The name of the route to map.

 

URL: The URL pattern for the route.

 

Defaults: An object that contains default route values.

 

The routes code snippet will be like as shown below.

 

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

Now we will learn how to create custom routing constraints in asp.net mvc.

What is Routing Constraint in Asp.Net MVC?

Basically, route constraints are a way to validate incoming URL parameters by using regular expressions in asp.net mvc. We will learn creating routing constraint with simple examples like allow only numbers and allow only alphabets,

Create Route Constraint to Allow Only Numbers

We want to restrict the Optional parameter (id) in our Route, which should only take only numbers as an input parameter. We will use Regular Expression in the below example of the route you can see how to apply constraints on Route. 

 

Here we are Allowing only numeric value as the Optional parameter. If we pass other than a numeric value, it will show an error for that we will use regular expression @"^[0-9] $" to allow only numbers.

 

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, constraints: new { id = @"^[0-9] $" });

Valid URL - http://localhost:1566/Default1/index/10

Invalid URL - http://localhost:1566/Default1/index/Mobile 

Create Route Constraint to Allow Only Alphabets

Now in above Route I want to restrict Optional parameter (id) which should take only   alphabets as a input parameter for that we are going to Use Regular Expression in below example of route you can see how to apply constraints on Route.

 

Here we are Allowing only Alphabets value as Optional parameter if we pass other than Alphabets. It will show an error for that we will use regular expression @"[a-zA-Z]*$" to allow only alphabets.

 

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, constraints: new { id = @"[a-zA-Z]*$" });

Valid URL - http://localhost:1566/Default1/index/Mobile 

Invalid URL - http://localhost:1566/Default1/index/10

 

Once we add the above constraints in our Routeconfig class, that will be like as shown below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace MVCDemo

{

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Default1", action = "Index", id = UrlParameter.Optional },

constraints: new { id = @"[a-zA-Z ]*$" });  //Alphabets allowed

 

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Default1", action = "Index", id = UrlParameter.Optional },

constraints: new { id = @"^[0-9] $" });  //Only Numbers

 

routes.MapRoute(

name: "Default1",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Default1", action = "Index", id = UrlParameter.Optional}

); // Default

}

}

}

 This is how we will use routing and routing constraints in asp.net mvc application.