WebAPI 核心路由问题

WebAPI Core routing issues

所以,我正在玩 Web API(ASP.NET Core 2)并且遇到路由问题。

我有几个控制器,例如:

学校控​​制器
教师控制器。

两人都获得了:Get(int id)

问题是,当我 运行 它时,我在实际能够调用这些方法之前得到一个 运行 时间错误。

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}'

当控制器应该有自己的 Gets 等时为什么要这样做...所以你可以这样做:

/api/{controller}/1

etc... ?

现在,我还有另一个 Get 方法,都在它们的控制器中,但具有不同的方法签名和不同的 HttpGet 名称,即:

// 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
    }
}

对于学校管理员:

[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
    }
}

要明确 - 问题是:

控制器不能对同一路由执行操作 Name。它们必须是唯一的,以便路由 table 可以区分它们。

引用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.

强调我的

更新路线名称

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

从两个控制器中删除 get 操作上的名称将解决问题