• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Sunday, August 30, 2020

Attribute Routing in ASP.NET Core MVC

 Admin     August 30, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     1 comment   

In this article, I am going to discuss Attribute Routing in ASP.NET Core MVC Application with examples. Please read our previous article before proceeding to this article where we discussed the Conventional Based Custom Routing in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers.
  1. Need and Use of Attribute Routing in ASP.NET Core MVC Application.
  2. What is Attribute Routing in ASP.NET Core MVC?
  3. Attribute Routing with Parameters in ASP.NET Core MVC Application
  4. Attribute Routing with Optional Parameters in ASP.NET Core MVC Application
  5. Controller and Action Method Names in Attribute Routing.
  6. Attribute Routes at Controller Level
  7. How to ignore the Route Template placed at the Controller Level?
Need and Use of Attribute Routing in ASP.NET Core MVC Application
Before understanding the Attribute Routing in ASP.NET Core MVC Application, let us first do some changes to our application. First, modify the Configure() method of the Startup.cs file as shown below. If you notice in the code, here we are using the UseMvc() method without passing the default route template as a parameter.
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMvc();
    }
}
With the above changes in the Configure method, now our application does not have any configured routes to handle the request and response.

Now Modify the Home Controller as shown below.
public class HomeController: Controller
{
    public string Index()
    {
        return "Index() Action Method of HomeController";
    }
}
Now, when you navigate to any of the following URLs, you will get the 404 errors. This is because at the moment we don’t have any configured route in our application to handle the request.
  1. http://localhost:52190
  2. http://localhost:52190/home
  3. http://localhost:52190/home/index
Let us see how to use Attribute Routing to map the incoming URLs to the Index action method of Home Controller.

Attribute Routing in ASP.NET Core MVC:
With the help of ASP.NET Core Attribute Routing, you can use the Route attribute to define routes for your application. You can use the Route attribute either at the Controller level or at the Controller Action Methods level. When you apply the Route attribute at the Controller level, then it is applicable for all the action methods of that controller.

Let us modify the Home Controller as shown below. Here we have applied the Route Attribute at the Action method.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        [Route("")]
        [Route("Home")]
        [Route("Home/Index")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }
    }   
}
If you notice, here we applied the Route() attribute 3 times on the Index() action method of Home Controller. The point that you need to remember is, with each instance of the Route attribute we specified a different route template. With the above three Route attribute, now we can access the Index() action method of the HomeController using the following 3 URLs.
  1. http://localhost:52190
  2. http://localhost:52190/home
  3. http://localhost:52190/home/index
Now run the application and navigate to the above three URLs and you will see the output as expected.

Attribute Routing with Parameters in ASP.NET Core MVC Application:
As we already discussed, with conventional based routing, we can specify the route parameters as part of the route template. We can also do the same with attribute routing. That means we can also define Route Attribute with parameters. To understand this, modify the Home Controller as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        [Route("")]
        [Route("Home")]
        [Route("Home/Index")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }
        [Route("Home/Details/{id}")]
        public string Details(int id)
        {
            return "Details() Action Method of HomeController, ID Value = " + id;
        }
    }   
}
As you can see in the above code, the Details() action method has the id parameter. Notice in the route template, we also specified the id parameter. So the URL (/Home/Details/10) will execute the Details(int id) action method and maps the value “10” to the “id” parameter of the Details action method. This is done by a process called Model binding which will discuss in our upcoming articles. Now, run the application and navigate to the following URL and you will see the output as expected.

http://localhost:52190/Home/Details/10

Attribute Routing with Optional Parameters in ASP.NET Core MVC Application:
Like conventional based routing, we can also make a parameter as optional in Attribute Routing. To make the Route parameter optional, simply add a question mark “?” at the end of the parameter.

In our example, at the moment, the Details(int id) action method of the HomeController is executed only if we pass the id parameter value. If we have not passed the id parameter value in the URL, then we will get 404. For example, at the moment if we navigate to the following URL we will get a 404 error.

http://localhost:52190/Home/Details Let us modify the Route attribute of the Details action method as shown below to make the route parameter “id” as optional by adding a “?” at the end.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        [Route("")]
        [Route("Home")]
        [Route("Home/Index")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }
        [Route("Home/Details/{id?}")]
        public string Details(int id)
        {
            return "Details() Action Method of HomeController, ID Value = " + id;
        }
    }   
}
Now run the application and navigate to the following URL and you will see the output as expected instead of 404 error.

http://localhost:52190/Home/Details/

Controller and Action Method Names in Attribute Routing:
With attribute routing in ASP.NET Core MVC Application, the controller name and action method names do not play any role. To understand this, modify the Home Controller as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        [Route("")]
        [Route("MyHome")]
        [Route("MyHome/Index")]
        public string StartPage()
        {
            return "StartPage() Action Method of HomeController";
        }
    }   
}
As you can see, we have specified the Route attribute three times StartPage() action method of the HomeController. So, this StartPage action method is going to be executed for the following 3 URLs.

/
/MyHome
/MyHome/Index


Attribute Routes at Controller Level:
In the ASP.NET Core MVC application, it is also possible to apply the Route() attribute on the Controller class as well as on individual action methods. If you want to make the attribute routing less repetitive, then you need to use the route attributes on the controller level as well as on the individual action methods level.

Let us understand this with an example. First, modify the Home Controller class as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        [Route("")]
        [Route("Home")]
        [Route("Home/Index")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }
        [Route("Home/Details/{id?}")]
        public string Details(int id)
        {
            return "Details() Action Method of HomeController, ID Value = " + id;
        }
    }
}
With the above code in place, we can access the Index() action method using the following 3 URLs.
/
/Home
/Home/Index

Along the same line, we can also access the Details(int? id) action method using the following 2 URLs.
/Home/Details
/Home/Details/2


If you notice, we have repeated the word Home multiple times (four times in our example). In order to make these routes less repetitive, we need to apply the Route() attribute with the word Home at the HomeController class level as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    [Route("Home")]
    public class HomeController : Controller
    {
        [Route("")]       
        [Route("Index")]
        public string Index()
        {
            return "Index() Action Method of HomeController";
        }
        [Route("Details/{id?}")]
        public string Details(int id)
        {
            return "Details() Action Method of HomeController, ID Value = " + id;
        }
    }
}
Note: The Route template applied on the controller level is prepended to the route template applied to the action method level.

Now when you navigate to the following four URLs you will get the output as expected.
Attribute Routing in ASP.NET Core MVC

However, when you navigate to the root URL (http://localhost:52190) of the application, you will get a 404 error. In order to solve this, you need to include the route template that begins with “/” on the Index() action method as shown below.
Attribute Routing in ASP.NET Core MVC Application

With the above changes in place, now run the application and navigate to the root URL and you will see the output as expected.

How to ignore the Route Template placed at the Controller Level?
In order to ignore the Route Template placed at the Controller level, you need to use / or ~/ at the action method level. If the action method route template starts with / or ~/, then the controller route template is not going to be combined with the action method route template.

To understand this let us modify the Home Controller class as shown below. In the following code, the About action method starts with ~/, so this action method is not going to be combined with the controller route template.
Understanding tilde in ASP.NET Core MVC Application

Now run the application and navigate to /About URL and you will see the output as expected.

That’s it for today. In the next article, I am going to discuss Tokens in Attribute Routing in ASP.NET Core MVC Application. Here, in this article, I try to explain Attribute Routing in ASP.NET Core MVC Application. I hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of Attribute Routing in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

1 comment:

  1. defneAugust 18, 2023 at 2:22 AM

    kuşadası
    milas
    çeşme
    bağcılar
    siirt
    ACW2N

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape