• Skip to content
  • Skip to primary sidebar
  • Home
  • Angular
  • ASP.NET Core
  • Entity Framework
    • Entity Framework 6
    • Entity Framework Core
  • Crystal Reports
  • C#
  • ASP.NET
  • About Us
    • Privacy Policy
    • Contact Us

TekTutorialsHub

Free Online Tutorials

Attribute Routing in ASP.NET Core

October 22, 2017 by TekTutorialsHub 2 Comments

Routing in ASP.NET Core
Route Constraints
 

In this article, we will look at the Attribute Routing in ASP.NET Core Apps. We learnt the basics of Routing in the last tutorial. Routing is how ASP.NET Core matches an incoming URL to a controller action.

There are two ways in which you can configure routing in ASP.NET Core. 

  1. Convention based Routing
  2. Attribute-based Routing

We learnt Convention based Routing in the last tutorial. We will look what is Attribute based routing in this article.

In this article

  • What is Attribute Routing
  • How to Setup Attribute Routing
  • How to Use Attribute Routing
    • Changing the Name of the Action Method
    • Multiple Routes
    • Token Replacement
    • Parameters to Action Methods
    • Combining Routes
    • Mixed Routing
    • Action Verbs
  • Summary

What is Attribute Routing

The attribute routing uses the attributes defined directly on the controller action to define the routes. Attribute routing gives you more control over the URLs in your web application.

In convention based routing all the routing is configured in the Startup class. In Attribute Routing routing is configured at the controller level.

How to Setup Attribute Routing

The Routes are added using the Route Attribute on the controller Action. The Route Attribute takes three arguments, URL Pattern, name and order.  

In the following code, we have added the route attribute on the index action method, passing “Home” as the URL Pattern.

HomeController.cs
1
2
3
4
5
6
7
8
 
public class HomeController: Controller{
    [Route("Home")]       
    public string Index(){
        return "Hello from Index method of Home Controller";   
    } 
}
 

In the above example, the /Home URL invokes the index method of the HomeController class. That is because The Route attribute expects the complete route to the action method.

 

How to Use Attribute Routing

Open the Project we created in the previous tutorial. 

Now, Open the startup.cs and locate the Configure method. Change the code as below

Startup.cs
1
2
3
4
5
6
7
8
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    if (env.IsDevelopment()) {
          app.UseDeveloperExceptionPage();
    }           
    app.UseMvc();     
}
 

 

Here, we are using the app.UseMvc(), which registers the MVC Middleware, with no route.

Now, Open the HomeController.cs.

Add the Route(“Home”) attribute to the index action method

HomeController.cs
1
2
3
4
5
6
 
[Route("Home")]
public string Index() {
    return "Hello from Index method of Home Controller";
}
 

When we call the URL /Home the Index Action method of the HomeController is invoked.

URLMatch ?Parsed As
/No
/HomeYesController=Home
Action=Index
/Home/IndexNo

Now change the URL Pattern to “Home/Index”.

HomeController.cs
1
2
3
4
5
6
 
[Route("Home/Index")]
public string Index() {
    return "Hello from Index method of Home Controller";       
}
 

URLMatch ?Parsed As
/No
/HomeNo
/Home/IndexYes
Controller=Home
Action=Index

Changing the Name of the Action Method

The Very important to note that the URL Pattern does not need to match the Controller and Action Name. 

For Example

HomeController.cs
1
2
3
4
5
6
 
[Route("Say/Hello")]
public string Index(){
    return "Hello from Index method of Home Controller";       
}
 

URLMatch ?Parsed As
/No
/HomeNo
/Home/IndexNo
/Say/HelloYesController=Home
Action=Index

 

Multiple Routes

You can also set multiple routes to a single action using Attribute Routing  as shown below

HomeController.cs
1
2
3
4
5
6
7
8
 
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public string Index(){
    return "Hello from Index method of Home Controller";       
}
 

URLMatch ?Parsed As
/Yes
Controller=Home
Action=Index
/HomeYesController=Home
Action=Index
/Home/IndexYes
Controller=Home
Action=Index
/Say/HelloNo

Token Replacement

The Attribute Routing makes it easier for us by providing the tokens for [area], [controller], and [action].

These tokens get replaced by their actual values in the Routes collection       

HomeController.cs
1
2
3
4
5
6
7
8
 
[Route("")]
[Route("[controller]")]
[Route("[controller]/[action]")]
public string Index() {
    return "Hello from Index method of Home Controller";       
}
 

The tokens in the URL Pattern ensures that the Controller and Action names stay sync with the name of the controller class.

Parameters to Action Methods

Just like in Convention based Routing, We can define additional URL Parameter placing them inside curly braces.  This can be passed as parameters to the action method.

1
2
3
4
5
6
7
8
9
10
11
12
 
[Route("")]
[Route("[controller]")]
[Route("[controller]/[action]/{id?}")]
public string Index(string id) {
   if (id !=null) {
     return "Received " + id.ToString();
   } else {
      return "Received nothing";           
   }       
}
 

In the above example, id is an Optional parameter. Any Value Received is injected as a parameter to Index Action method.

Combining Routes

We can specify the route attributes on the Controller class. Any URL pattern defined in the Controller class is prepended to the URL Pattern in the Action method.

HomeController.cs
1
2
3
4
5
6
7
8
9
 
[Route("Home")]   
public class HomeController : Controller {       
    [Route("Index")]       
    public string Index() {
        return "Hello from Index method of Home Controller";       
    }    
} 
 

This works fine for the Route Home/Index.  If the Pattern begins with a /  are considered to be absolute path and do not get combined with the parent URL Pattern 

This Following will not work with the URL Home/Index.     

HomeController.cs
1
2
3
4
5
6
7
8
9
 
[Route("Home")]   
public class HomeController : Controller {       
    [Route("/Index")]       
    public string Index() {
        return "Hello from Index method of Home Controller";       
    }    
} 
 

 

Mixed Routing

You can use both convention-based routing and attribute routing in the same project. However,  if you define attribute routing on an action, then convention based routing cannot be used on that Action. 

Action Verbs

Attribute route can also be used with HTTP verb attributes like HttpGet, HttpPost etc.      

HomeController.cs
1
2
3
4
5
6
7
8
 
[HttpGet("")]
[HttpGet("Home")]
[HttpGet("Home/Index")]
public string Index() {
    return "Hello from Index method of Home Controller";       
}
 

Summary

We looked at How to setup and work with attribute routing in ASP.NET Core Apps. We Register the URL Pattern in the Route Attribute on the controller Action methods. 

Routing in ASP.NET Core
Route Constraints
 

Filed Under: ASP.NET Core Tagged With: Routing

2
Leave a Reply

wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Lexi

Thanks – this was very helpful. What about multiple parameters – How would I create an endpoint to the request https://localhost:44329/api/scoInfo?activityId=1&studentId=1&timestamp=1527357844844 using attribute routing in the controller?

Vote Up0Vote Down  Reply
May 27, 2018 2:29 am
TekTutorialsHub

create a view model

1
2
3
4
5
6
7
 
student {
  public string  activityId {get;set;}
  public int  studentId {get;set;}
  public string  timestamp{get;set;}
}
 

And in controller

1
2
3
4
5
6
7
8
 
[Route("api")]   
public class apiController : Controller {       
   [HttpGet("/scoInfo")]
   public method scoInfo([FromQuery] Student student)
   {  }
}
 

Vote Up0Vote Down  Reply
May 27, 2018 3:06 pm

Primary Sidebar

Copyright ©2008-2018

About us Contact Privacy Policy

Feb,21,2019 03:51:44 PM

Copyright © 2019 · Magazine Pro on Genesis Framework · WordPress · Log in

wpDiscuz
Our web site uses cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.OkRead more