WebAPI Core routing issues

Ahmed ilyas picture Ahmed ilyas · Jan 29, 2018 · Viewed 12.9k times · Source

So, I am playing around with Web API (ASP.NET Core 2) and having routing issues.

I have several controllers such as:

SchoolController
TeacherController.

Both have Gets: Get(int id)

Problem is that when I run it, I get a runtime error before even actually being able to invoke the methods.

Attribute routes with the same name 'Get' must have the same template:
Action: MyProject.WebAPI.Controllers.SchoolController.Get (MyProject.WebAPI)' - Template: 'api/school/{id}'
Action: MyProject.WebAPI.Controllers.TeacherController.Get (MyProject.WebAPI)' - Template: 'api/teacher/{id}'

Why would it do this when the controllers should have their own Gets etc... so you can do:

/api/{controller}/1

etc... ?

Now, I also have another Get method, both in their controllers but with a different method signature along with a different HttpGet name i.e:

// TeachersController:

[Produces("application/json")]
[Route("api/teacher")]
public class TeacherController : Controller
{

    // GET: api/Teacher/5
    [HttpGet("{id}", Name = "Get")]
    public IActionResult Get(int id)
    {

        // BLAH
    }
}

And for the school controller:

[Produces("application/json")]
[Route("api/school")]
public class SchoolController : Controller
{

    [HttpGet("{id}", Name = "Get")]
    public IActionResult Get(int id)
    {
        // BLAH
    }

    [HttpGet("SearchBasic")]
    public IActionResult SearchBasic(string schoolName, string zipCode)
    {
        // BLAH
    }
}

To be clear - the question is:

  • Why do I get the runtime errors as soon as the web app is started?

  • The get's are on different controllers, so why would there be any conflicts?

Answer

Nkosi picture Nkosi · Jan 29, 2018

Controllers can't have actions with the same Route Name. They must be unique so that the route table can differentiate them.

Reference Routing to Controller Actions : Route Name

Route names can be used to generate a URL based on a specific route. Route names have no impact on the URL matching behavior of routing and are only used for URL generation. Route names must be unique application-wide.

emphasis mine

Update route names

[Route("api/teacher")]
public class TeacherController : Controller {

    // GET: api/Teacher/5
    [HttpGet("{id}", Name = "GetTeacher")]
    public IActionResult Get(int id) {
        //...
    }
}

[Route("api/school")]
public class SchoolController : Controller
{
    // GET: api/school/5
    [HttpGet("{id}", Name = "GetSchool")]
    public IActionResult Get(int id) {
        //...
    }
}