WebAPI Core Routing Issues

So, I am playing with the Web API (ASP.NET Core 2) and have problems with routing.

I have several controllers, such as:

SchoolController
TeacherController.

Both have gets: Get(int id)

The problem is that when I run it, I get an error at runtime, even when you actually call 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 do this when controllers must have their own Gets, etc., so that you can:

/api/{controller}/1

etc... ?

Now I also have another Get method, both in their controllers and with a different method signature, as well as with a different name HttpGet ie:

// 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 am I getting runtime errors right after launching a web application?

  • The resulting files are on different controllers, so why are there conflicts?

+17
2

Name . , .

:

URL- . URL- URL-. .

[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) {
        //...
    }
}
+22

+7
source

Source: https://habr.com/ru/post/1692852/


All Articles