Create Custom Route Constraints in Asp.Net MVC with Example

  Total Views : 1816
  Comments : 0
 
  Keywords : Asp.net mvc create route constraints with example,Asp.net mvc creating custom route constraints with example, How to use 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 have look on asp.net webforms url to know how it was mapped. Let's take sample url like http://localhost:2157/UserDetails/Admin.aspx/EmpId=10 this URL will tell that there is UserDetails folder on server and inside that we have page with name Admin.aspx and it is accepting EmpID=10 as Query string and its difficult to remember this url. In Asp.net Webforms we directly map User request to Physical files on Server.

 

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

How Asp.Net MVC URL Routing will Work?

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

 

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

Understand How to declare Default Route

Routing file is stored in App_Start folder of our project with 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 App_Start folder inside that we can find RouteConfig.cs. This is default route which is provide by 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

For creating 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.

 

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 is 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

Now in our Route we want to restrict Optional parameter (id) which should take only numbers as an 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 numeric value as Optional parameter if we pass other than numeric value then it will show error for that we are going to 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 then it’s going to show error for that we are going to 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 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 applciation.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User