Adding routes via route attributes

Adding routes via route attributes is a way of defining the route for every controller action as an attribute on top of controller action methods.

Within the controller class (in our case, HomeController), add the Route attribute before the Index method:

[Route("Home/Index")]public IActionResult Index(){    return View();}

This instructs ASP.NET Core MVC to pass requests to the Index method whenever the URL looks like http://example.com/Home/Index. As patterns are not supported in attribute routing, if we want to make the Index method of HomeController the default of the application, then we need to add multiple Route attribute calls on top of the Index method:

[Route("")][Route("Home")][Route("Home/Index" ...

Get Hands-On Full-Stack Web Development with ASP.NET Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.