How to use Attribute Routing in ASP.NET MVC 5

In this tutorial, we will learn how to use attribute routing in ASP NET MVC 5. We will create an actual project and then enable and apply attribute routing. This way, we can understand how attribute routing can help us control our website’s structure.

What is Routing in MVC?

Routing maps the URL to an Action in a controller class. Routing contains URL patterns and handler information. We can configure the route in the ASP.NET MVC application in the RouteConfig class.

Attribute-based routing is a feature where you can apply attributes to a controller level or directly from an action result method. By default, convention-based routing is enabled on your project during creation. If you open your RouteConfig class inside the App_Start folder, this is what you will find. Below are the route config used on all of your controllers in your project.

http://localhost:xxxx/Controller Name/Action/{parameter:id}

– Default URL format
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.Mvc;
 using System.Web.Routing;
  
 namespace MVCAttributeDemo
 {
     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 }
             );
         }
     }
 }
   

We can define multiple routes using this route config class, but this can create a conflict if not configured correctly. So, in this case, we will use attribute-based routing instead.

Now, Before we proceed please make sure to install the Visual Studio from this link.

I. Setup ASP.NET Web Application Project

Let’s start by creating a new ASP.NET Web Application. Open your Visual Studio IDE and proceed with the steps below.

  • Select File » New » Project.
  • Choose ASP.NET Web Application(.NET Framework). Name the project MVCAttributeDemo to have the same namespace as my project. Click OK.
  • Select the MVC template and then check Configure for HTTPS.
  • Lastly, Click on Create.
ASP.NET Web Application

II. Enabling Attribute Routing

The first thing that we need to do is enable attribute routing. We will enable attribute routing along with convention-based routing. To do that, we need to declare the following code on the route config class.

 routes.MapMvcAttributeRoutes();

Adding the code right above the MapRoute config. See the code snippet below.

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.Mvc;
 using System.Web.Routing;
  
 namespace MVCAttributeDemo
 {
     public class RouteConfig
     {
         public static void RegisterRoutes(RouteCollection routes)
         {
             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

             routes.MapMvcAttributeRoutes();
  
             routes.MapRoute(
                 name: "Default",
                 url: "{controller}/{action}/{id}",
                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
             );
         }
     }
 }

III. Add Framework Controller

We will apply the attribute route on this controller. To create the controller follow the steps below.

  1. Right-click on the Controllers folder.
  2. Select Add then choose Controller.
  3. Choose MVC 5 Controller – Empty then click the Add button
  4. Name the controller FrameworkController then press the add button.
Controller in ASP NET MVC Application
Steps 1 and 2
ASP NET MVC 5 Controller
Step 3
FrameworkController
Step 4

After successfully adding the controller, this is how the new controller looks like from the solution explorer.

Adding a COntroller ASP NET
Framework Controller

IV. Add methods and View in the Framework Controller

Once we have our controller. Open the Framework controller and add the following method.

 public class FrameworkController : Controller
  {
         // GET: Framework
         public ActionResult Angular()
         {
             return View();
         }
         public ActionResult React()
         {
             return View();
         }
         public ActionResult Blazor()
         {
             return View();
         }
 } 

In this part, we have added 3 New Action Methods Angular, React, and Blazor in Framework Controller.

Adding a Controller

After that, create views for each action method. See the image shown below.

Adding View in ASP NET MVC

V. Default MVC URL

As define route on the route config class. A controller can be accessed using this format. http://{root URL}/{controller}/{action}/{parameter}. So in this project, the methods in the framework controller can be accessed using the following URL.

Action ResultROUTE URL
Angular()https://localhost:44398/Framework/Angular
React()https://localhost:44398/Framework/React
Blazor()https://localhost:44398/Framework/Blazor

VI. Add Route attribute

Let’s add the route attribute to the Framework controller methods. Using this technique, we can define whatever route we want for every method on this controller. To do that, apply this attribute to the Action method.

Action ResultAttribute RouteRoute URL
Angular()[Route(“AngularFramework”)]https://localhost:44398/BlazorFramework
React()[Route(“ReactFramework”)]https://localhost:44398/ReactFramework
Blazor()[Route(“BlazorFramework”)]https://localhost:44398/BlazorFramework
Route attribute URL
using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.Mvc;
 namespace MVCAttributeDemo.Controllers
 {
     public class FrameworkController : Controller
     {
         // GET: Framework
         [Route("AngularFramework")]
         public ActionResult Angular()
         {
             return View();
         }
         [Route("ReactFramework")]
         public ActionResult React()
         {
             return View();
         }
         [Route("BlazorFramework")]
         public ActionResult Blazor()
         {
             return View();
         }
     }
 }

VI. Add Route Prefix attribute

We can use Route prefixes if you have a common name on your route attribute methods. For example, if you have the same route attribute assigned, just like the attribute on the image below.

Routing in ASP.NET MVC
Route Prefixes

If you observed Framework word is repeated multiple times in an attribute. This scenario is where the route prefix attribute comes in handy. We can use the Route prefix to define the Framework on the controller level, and this prefix can be applied to all the methods inside the framework controller. To specify the Route prefix, use this attribute.

RoutePrefix("Framework")

Once, applied this is how your Framework controller will look like.

RoutePrefix in ASP.NET MVC

Now, you can access the methods using the URL below.

https://localhost:44398/RoutePrefix/BlazorFramework

– RoutePrefix(“Framework”)
Action ResultAttribute RouteRoute URL
Angular()[Route(“AngularFramework”)]https://localhost:44398/Framework/BlazorFramework
React()[Route(“ReactFramework”)]https://localhost:44398/Framework/ReactFramework
Blazor()[Route(“BlazorFramework”)]https://localhost:44398/Framework/BlazorFramework
Route Prefix

VII. Add Route Areas attribute

Suppose you are using Area in your project. This step is how you can define route attributes in an Area. To be able to do a demo on using attribute route from an Area. Let’s add an Area to our project.

Create an Area

  1. Right-click on your Project Solution
  2. Choose Add » New Scaffolded Item
  3. Select MVC 5 Area and click the Add button.
  4. Name it JavaScript and press the Add button.
Add new Scaffold
Step 1 and 2
how to use attribute routing in ASP NET MVC 5
Step 3
ASP NET MVC Area
Step 4

Now, create a sample controller inside the Javascript Area. To do that, follow the steps below.

Create a Controller inside Javascript Area

  1. Create a Controller, name it JavascriptFramework
  2. Add a new action result method Vue and Angular, in your controller. See the image below.
  3. Create a view of each method.
  4. Then apply the route attribute.
how to use attribute routing in ASP NET MVC 5
Step 1
how to use attribute routing in ASP NET MVC 5
Step 2
how to use attribute routing in ASP NET MVC 5
Step 3
how to use attribute routing in ASP NET MVC 5
Step 4

Since we define route attributes like this.

[RouteArea("Javascript")] 
[RoutePrefix("JavascriptFramework")]

We can access the Area Controller method using this URL format:

https://localhost:xxxx/Route Area/Route Prefix/Action Result method

URL format
Action ResultROUTE URL
Vue()https://localhost:44398/Javascript/JavascriptFramework/Vue
AngularJS()https://localhost:44398/Javascript/JavascriptFramework/AngularJS

VIII. Add Route Constraints

This part will add 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.

Below is a sample of what route constraints will look like.

  1. Integer parameter:
[Route("AngularFramework/{id:int}")]

2. string parameter:

[Route("ReactFramework/{type:regex(^[a-zA-Z]*$)}")]
how to use attribute routing in ASP NET MVC 5
Route Constraint

Below is the Table of Constraints. You can refer below for available 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 length{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}S)}
Table of Constraints

This is how to use attribute routing in ASP NET MVC 5. You may also download the source code for this tutorial on my GitHub Account @coderbugzz.

Summary

We learned from this tutorial how to use attribute routing in ASP NET MVC 5. We also tried to route in Areas. Hopefully, this tutorial will help you if you are having trouble creating a custom route on your ASP.NET Application.

KEEP CODING!!

Read More : Secure ASP.NET Web Application

– freecodespot