articles

Home / DeveloperSection / Articles / Attribute Routing in ASP.NET MVC

Attribute Routing in ASP.NET MVC

Anupam Mishra5914 09-Mar-2016
Introduction:

Attribute Routing is an important feature of MVC web applications. Routing enables the use of URL that are described by user action and more understood by users. We can hide information which is not shown to final users in a URL bar.

Attribute Routing in ASP.NET MVC

 

Routing is how my application matches a URI to an action. A URI is a combination of URL (Uniform Recourse Locator) and URN (Uniform Recourse Name).MVC supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives to more control over the URIs in our web application. 

A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. 

Why Attribute Routing?
 1. URL Keep Clean: 

   For example, we are using conventional URL structure are ‘https://www.myurl.com/Students/Default.aspx? studentId=10&view=details’

But in MVC, we are defining a URL Structure much cleaner and understood by

 End user as like this: - ‘https: //www.myurl.com/ Students /details/10’

 2. For URLs discoverable by end-users.

 3. We have avoid database IDs in URL.

 4. Clean URLs is good for SEO. And various one. 

Default Route Declaration:

By default, we are given a route that will probably match most, if not all of your routes, and are asked to define if there are any more specific routes we would also like to handle.

In below are a by default, routes might look like this:

publicclassRouteConfig
    {
        publicstaticvoid 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 }
            );
        }
    }

 In above, routes is a Route table of type RouteCollection type, i.e. is stored all possible routes of the given URL pattern and specified controller in the application. If we want to add new route then we are using MapRoute that’s added the route in the Routetable.   IgnoreRoute is ignored URL structure that is not matched with specified one. We have also defined a Optional URI Parameter with the using a question mark (?). For Example, Route (“home/ {id?}”) in controller sideaction.  

Defining Routing in ASP.NET MVC:

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


Attribute Routing in ASP.NET MVC


Route Constraints:

 We restrict how the parameters in the route template are matched. For example:

 I have shown how to search certain student by their id. Now, let's say we also want the end user to search student byname. 

Student/3 render view with id
Student/Anupam  render view with Name

  For byname, we can add another ActionResult which receives a string parameter.

But it is not sufficient find by name so since we can explicitly define a route for

diverting to by name action.
[Route("Student/{id:int}"]

public Student GetStudentById(int id) { }



[Route("Student/{name}"]

public Student GetStudentByName(string name) { }

 

Here, the first one is only applicable when the "id" segment of the URI is an integer. Otherwise, the second one will be chosen.

 What is better?

In the developer opinion, Attribute Routing is better vs Convectional Routing, because it will give a more flexible over conventional. But, if we want to better security and routing parameter in controller level as well as route table both are playing individually an important role, so in this case, the decision is yours. 

Additional Resources: 

  1. https://www.mindstick.com/Articles/757/routing-in-asp-dot-net-mvc
  2. https://msdn.microsoft.com/en-us/library/cc668201.aspx


Leave Comment

Comments

Liked By