Attribute Routing – Session 26

Attribute Routing - Session26

In this session of ASP.NET Core Tutorial, we are going to discuss about Attribute Routing. Generally, ASP.NET Core supports two types of routing which are Conventional & Attribute Routing. We discussed about Conventional routing during session 12. The routing which we are going to talk about in this session (Attribute Routing), is proper option for WEB API application and it is implemented by Attributes that we can use on Action Method or Controller level.

What is Attribute Routing?

One of the routing system in ASP.NET Core that is suitable for WEB API application. Also, as its name implies, routing is based on Attributes that can be applied on Action Method or Controller level.

Implement Attribute Routing

To implement attribute routing, we should change “UseEndpoints” middleware in “Configure” method, under “Startup” class. During session 12 we implemented conventional routing through adding below code.

But, in this session for converting routing to Attribute Routing, we should replace below code to above code.

Then, we can use “Route” attribute for routing in Controller and Action Method. This routing can be in Action Method level.

Moreover, we can implement Route attribute in Controller level.

Furthermore, instead of static routing same as “Home” or “Index”, we can use “[controller]” token for Controller route and “[action]” token for Action Method route. In case of using Tokens, routes would be same as Conventional Routing and the URL would be based on Controller and Action Method Name. While, if we use static words same as “Home” or “Index”, name of Controller and Action Method are not important anymore in the URL.

Also, for URL input parameter we can use [Route(“{id}”)] . moreover, for making input parameters optional we can use ? to the attribute route [Route(“{id?}”)].

For making Action Method input parameters optional, we can use ? mark to end of its type. For example public IActionResult Detail(int? id). Also, this technique does not work for all the types same as String type.

CostData = costRepository.GetCostByID(id??1) in this line of code ?? means, if “id” is null use 1 as default value.

If you need more details, watch this session video. Also, for being updated about our coming sessions, follow us on Instagram, Facebook, Telegram or YouTube. Also you can have access to list of all sessions HERE.

You can download this Session Slides form HERE

0.00 avg. rating (0% score) - 0 votes


0 0 votes
Article Rating

Inline Feedbacks
View all comments