Until now, we have used convention-based routing. In convention-based routing, we define the routing templates (which are just parameterized strings) in a centralized place these are applicable to all the available controllers. The problem with convention-based routing is that, if we want to define different URL patterns for different controllers, we need to define a custom URL pattern that is common to all the controllers. This makes things difficult.
There is another option for configuring the routing engine-attribute-based routing. In attribute-based routing, instead of configuring all the routing in a centralized location, the configuration will happen at the controller level.
Let us see an example of attribute-based routing.
First, let us remove the convention-based routing that we created earlier in the Configure
method in the startup.cs
class file:
public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseMvc(); //app.UseMvc(routes => //{ // routes.MapRoute(name: "FirstRoute", // template: "Hello", // defaults: new { controller = "Home", // action = "Index2" }); // routes.MapRoute(name: "default", // template:" // {controller=Employee}/{action=Index}/{id?}"); //}); }
Then, we can configure the routing at the controller itself. In the following code, we have added the routing configuration for the home
controller that we created earlier:
namespace Validation.Controllers { public class HomeController : Controller { // GET: /<controller>/ [Route("Home")] public IActionResult Index() { return Content("Index action method"); } [Route("Home/Index3")] public IActionResult Index2() { return Content("Index2 action method"); } } }
We have used the Route
attribute in the action
methods of the controller. The value passed in the Route
attribute will be acting as the URL pattern. For example, when we access the URL http://localhost:49831/Home/
, the Index
method of HomeController
will be called. When we access the URL http://localhost:49831/Home/Index3
, the Index2
method of HomeController
will be called. Please note that the URL pattern and action
method name do not need to match. In the preceding example, we are calling the Index2
action method but the URL pattern uses Index3
, http://localhost:49831/Home/Index3
.
When you use attribute-based routing and convention-based routing together, attribute-based routing will take precedence.