Using attribute routing on a controller is forcing me to manage all routes

1.4k views Asked by At

I am just getting to grips with Asp.net Core and I'm trying to set up a basic site.

I want to build an admin panel that is under a subdirectory.

I have a simple controller which was scaffolded by the EF crud feature.

So it seems that from the examples I should just be able to add a [Route()] attribute to the controller and it will prefix everything. Something like this:

[Route("Admin/Subfolder/[controller]")]
public class EventsController : Controller
{
}

But when I do that I just get an error page saying "multiple actions matched" and it lists index, details, create, etc.

I can get it working if I then go through every method and put a [Route()] attribute on it but this doesn't seem to be in line with the documentation.

It feels like I should be able to just add a prefix to the controller route without having to take over management of every route within the controller. Case in point, the POSTS are not working now and I'm not sure what the format of the route attribute should be for them.

What am I doing wrong?

1

There are 1 answers

2
Ross On BEST ANSWER

You are doing it correctly. Default route attribute can be applied at the controller level. “Placing a route attribute on the controller makes all actions in the controller use attribute routing.” Can you post complete code of your controller? There must be something else going on in there. Make sure you use HttpPost/HttpGet attribute for actions with the same name, like so:

[Route("Admin/Subfolder/[controller]")]
public class EventsController : Controller
{
    [HttpGet]
    public IActionResult NewEvent()
    { }

    [HttpPost]
    public IActionResult NewEvent()
    { }
}

Good explanation on routing can be found here