Benk
Benk

Reputation: 1312

Add Default action in the route attribute

How to set default action using Route attribute

[Route("cars/[action]")]
public class CarsRegistrationController : Controller
{
    public IActionResult Index()
    { ... }
}

cars/index works but if i go to /cars (without entering action name) i want it to redirect to default action index /cars/index

I tried modifying the Route to: no luck, How do I fix the syntax

[Route("cars/{action=index}")]
[Route("cars/[action:index]")]

Upvotes: 2

Views: 2957

Answers (1)

adolja
adolja

Reputation: 189

As you can read in the documentation of ASP.NET Core (https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing) putting a route on a controller means that it will combine with the routes on its actions.

[Route("[cars]")]
public class CarsRegistrationController : Controller
{
   [Route("~/cars")]   // Matches "~/cars"
   [Route("")]         // Matches "~/cars/Index"
   public IActionResult Index() => View();
}

Upvotes: 5

Related Questions