Advanced Routing in MVC

In this article, I am going to discuss the ideas about Advanced Routing in MVC with examples. Please read our previous articles before moving on to this article where we discussed Routing in ASP.NET MVC. As part of this article, we are going to discuss the following contents which are related to Advanced Routing in MVC.

Multiple Routes:

Route customization is an advanced topic. In this session, we will look at customize the multiple routing in the MVC application. You can configure the multiple routes using the Map Route extension method in RouteConfig.cs. This method needs at least two parameters such as route name and URL pattern and URL parameter is optional. If you need to pass some value to action using parameters then the parameter is mandatory.

While requested URLs come to the application. It is start compared to route patterns in order the pattern sequence in the route dictionary or order of added the route in RouteConfig.cs file. If request URLs are matched with the first URL pattern of the route dictionary, then it will call the specified controller and action. In case if URL is not matched with a pattern of the route dictionary, then it will call the default map route method and executed the default controller and action. Similarly, you can able to your own route map in routeconfig.cs file. Advanced Routing in MVC
Example -1
Route Configuring: – routeconfig.cs

1public static void RegisterRoutes(RouteCollection routes)
2{
3    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
4    routes.MapRoute(
5        name: "EmployeeDetails",
6        url: "EmployeeDetails/{id}",
7        defaults: new { controller = "Employee", action = "Details", id = UrlParameter.Optional }
8    );
9     
10    routes.MapRoute(
11        name: "Default",
12        url: "{controller}/{action}/{id}",
13        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
14    );
15}

Attribute Routes:

ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this routing, attributes are used to define routes. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

Enabling Attribute Routing

To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration. Advanced Routing in MVC

  • You must have enable attribute route in routeconfig.cs file. 
  • It must be enable before the default route.
1public static void RegisterRoutes(RouteCollection routes)
2{
3    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
4    routes.MapMvcAttributeRoutes();
5    routes.MapRoute(
6        name: "Default",
7        url: "{controller}/{action}/{id}",
8        defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
9    );
10}

Defining Attribute Routing in ASP.NET MVC

  • Controller level attribute routing
  • Action level attribute routing Advanced Routing in MVC

Controller level attribute routing

You can define routes at the controller level which apply to all actions within the controller unless a specific route is added to an action.

1using System.Collections.Generic;
2using System.Linq;
3using System.Web.Mvc;
4using ModelMVC.Models;
5 
6namespace ModelMVC.Controllers
7{
8    [RoutePrefix("Employee")] //Route Prefix Employee
9    [Route("{action=index}")] //default action
10    public class EmployeeController : Controller
11    {
12        public ActionResult Index()
13        {
14            var empDetails = from emp in GetEmpolyeeDetails()
15            select emp;
16            return View(empDetails);
17        }
18        [NonAction]
19        public List GetEmpolyeeDetails()
20        {
21            List employeeList = new List()
22            {
23            new EmployeeModel {ID=1, Name="King", Location="London" },
24            new EmployeeModel {ID=2, Name="Lipsh", Location="Bangalore" },
25            new EmployeeModel {ID=3, Name="Rio", Location="Sydney" }
26            };
27            return employeeList;
28        }  
29     
30        //Route: /Employee/About
31        public ActionResult About()
32        {
33            ViewBag.Message = "Your application description page.";
34            return View();
35        }
36    }
37}
Advanced Routing in MVC

Action level attribute routing

You can define routes at the action level which apply to a specific action within the controller.

1[Route("EmployeeDetails/{id}")]
2public ActionResult EmployeeDetailsbyID(int id)
3{
4}

Pass Multiple Parameter to MVC Action:

Now we will discuss multiple parameter pass to action. you can define the rules in routeconfig.cs file and also attribute route.
For example, the following route applies a multiple parameter pass to action.

routeconfig.csAdvanced Routing in MVC

1public static void RegisterRoutes(RouteCollection routes)
2{
3    routes.MapRoute(
4    "EmployeeByJoinDate",
5    "Employee/Join/{year}/{month}",
6    new { controller = "Employee", action = "EmployeeByJoinDate"});
7}

Attribute Routes with Multiple Parameters:

In this case, you can also apply the rules in the controller on the attribute level.

1[Route("Employee/Join/{year}/{month}")]
2public ActionResult EmployeeByJoinDate(int year, int month)
3{
4}

Above both examples will work as same. Advanced Routing in MVC

Route Constraints:

It will restrict the value of parameters by configuring route constraints and attribute route constraints. 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

Normal Route : Advanced Routing in MVC

1public static void RegisterRoutes(RouteCollection routes) {
2    routes.MapRoute(
3        "EmployeeByJoinDate",
4        "Employee/Join/{year}/{month}",
5        new { controller = "Employee", action = "EmployeeByJoinDate"},
6        new { year = @"d{4}", month = @"d{2}"}
7    );
8}

Attribute Routes: Advanced Routing in MVC

1[Route("Employee/Join/{year:regex(\d{4})}/{month:regex(\d{2})}")]
2public ActionResult EmployeeByJoinDate(int year, int month)
3{
4}

List of in-line Route Constraints

ConstraintDescriptionExample
alphaMatches uppercase or lowercase Latin alphabet characters (a-z, A-Z){x:alpha}
boolMatches a Boolean value.{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value.{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(6)}
{x:length(1,20)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}
rangeMatches an integer within a range of values.{x:range(10,50)}
regexMatches a regular expression.{x:regex(^d{3}-d{3}-d{4}$)}

Route Prefixes:

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute.
Use a tilde (~) on the method attribute to override the route prefix.

1[RoutePrefix("Employee/Details")]
2public class EmployeeController : Controller
3{
4    // GET Employee/Details
5    [Route("")]
6    public IEnumerable EmployeeDetails() {
7    //...
8    }
9 
10    //Employee/Details/12
11    [Route("{id:int}")]
12    public EmployeeModels EmployeeDetailsByID(int id) {
13    //...
14    }
15 
16    //employeemodels/Employee/Join/2018/02
17    [Route("~/Employee/Join/{year:regex(\d{4})}/{month:regex(\d{2})}")]
18    public HttpResponseMessage EmployeeByJoinDate(int year, int month) {
19    //...
20    }
21}

Warm UP- Advanced Routing in MVC

  • Configure the multiple routes using Map Route extension method in RouteConfig.cs.
  • Pass multiple parameter to action by using Route Configuring or Attribute Routes.
  • Restrict the value of parameter using Route Constraints on Route Configuring or Attribute Routes.
  • You can set a common prefix for an entire controller by using the [RoutePrefix] attribute.
  • Use a tilde (~) on the method attribute to override the route prefix.

Leave a Comment

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