In the previous tutorial, I have discussed what is Routing in ASP.NET Core? and how Routing Engine works in ASP.NET? and how to add custom routing in ASP.NET Core 2.0 Application. But now in this tutorial, we will discuss Attribute routing.
Previous tutorial series of ASP.NET Core 2.0
- Introduction to ASP.NET Core 2.0
- How to create a new project in ASP.NET Core 2.0 using Visual Studio.
- Project Folder structure and responsibility of each file in ASP.NET Core 2.0 Application.
- Middleware in ASP.NET Core.
- Routing in ASP.NET Core.
Attribute Routing in ASP.NET Core 2.0 Application.
Attribute-based routing is another approach to Routing. This is very simple and easy to understand. We can use C# Attributes in our controller classes and on the methods internally in these classes with the Attribute based routing. The Attribute-based routing is an alternative approach to the convention-based routing approach. Let’s see what is the difference between Convention-based routing and Attribute-based routing?
In this approach, you define the global URL format that application accepts. You can define multiple URL formats in one application. So, these formats map to the specific action methods on given controller. E.g. If your application receives a request, then routing engine will match it to one of the defined URL formats. And if any matches found, then It will forward the request to a specific controller with specific action method.
The convention-based approach is discussed in the previous tutorial.
In this approach, you specify routing information by decorating your controllers and action methods with attributes that define the application routes. This below code is the example of Attribute routing.
Let’s take a simple example. Open the project that we have created in the previous tutorial. Open student controller and write the below code in the student controller.
Now, let’s run your application, you will see the default output home page. But when you specify the /myStudent, the application should invoke the Index action method of student controller. Let’s run the application with this URL http://localhost:65388/myStudent/ and you will see index view of student controller. And same as if you specify the /studentName just after the myStudent, then you will see the application should invoke the Name action method from student controller.
If you want to show the controller name with the segment of URL, then you can use a token controller just inside the square brackets. This tells the ASP.NET MVC to use the name of this controller in this position. You can see the implementation in the below code.