gpt4 book ai didi

c# - WebAPI 核心路由问题

转载 作者:IT王子 更新时间:2023-10-29 04:54:12 24 4
gpt4 key购买 nike

因此,我正在使用 Web API (ASP.NET Core 2) 并遇到路由问题。

我有几个 Controller ,例如:

学校 Controller
教师 Controller 。

两者都有获取: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}'

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

/api/{controller}/1

etc... ?

现在,我还有另一个 Get 方法,都在它们的 Controller 中,但具有不同的方法签名和不同的 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
}
}

对于学校 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
}
}

要清楚 - 问题是:

  • 为什么 Web 应用一启动就出现运行时错误?

  • get 在不同的 Controller 上,为什么会发生冲突?

最佳答案

Controller 不能有具有相同路由 名称 的操作。它们必须是唯一的,以便路由表可以区分它们。

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

关于c# - WebAPI 核心路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com