REST Web API 2调用了动作方法而不被调用 [英] rest web api 2 makes a call to action method without invoked
问题描述
我正在关注位于此处的教程: https://docs.asp.net/en/latest/tutorials/first-web-api.html
我正在iis express中运行Web api,并使用邮递员通过以下路径调用它:
http://localhost:5056/api/todo
此调用命中了构造函数,然后以某种方式调用了
GetAll
函数从不被调用,甚至没有HttpGet
动词. 怎么称呼?
I am following a tutorial located here: https://docs.asp.net/en/latest/tutorials/first-web-api.html
and i am running the web api in iis express and call it using postman with the following path:
http://localhost:5056/api/todo
this call hits the constructor and then somehow calls the
GetAll
function which is never called and does not even have HttpGet
verb. How is it getting called?
namespace TodoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
public TodoController(ITodoRepository todoItems)
{
TodoItems = todoItems;
}
public IEnumerable<TodoItem> GetAll()
{
return TodoItems.GetAll();
}
[HttpGet("{id}", Name="GetTodo")]
public IActionResult GetById(string id)
{
var item = TodoItems.Find(id);
if (item == null)
return HttpNotFound();
return new ObjectResult(item);
}
public ITodoRepository TodoItems { get; set; }
}
}
推荐答案
控制器中的所有方法都是默认的HttpGet.您无需显式指定HttpGet动词. 如果您使用的是WebApiConfig中指定的默认路由,请调用 http://localhost:5056/api/todo 它将路由到控制器中的第一个无参数功能.您的情况是GetAll().
All methods in the controller are per default HttpGet. You don't need to specify the HttpGet verb explicit. If you are using the default route specified in the WebApiConfig and call the http://localhost:5056/api/todo it will route to the first parameterless function in the controller. In your case GetAll().
如果要指定路由,可以使用属性RoutePreFix和Route
If you want to specify the routing you can use the attributes RoutePreFix and Route
namespace TodoApi.Controllers
{
[RoutePrefix("api/[controller]")]
public class TodoController : Controller
{
public TodoController(ITodoRepository todoItems)
{
TodoItems = todoItems;
}
Route("First")]
public IEnumerable<TodoItem> GetAll1()
{
return TodoItems.GetAll();
}
[Route("Second")]
public IEnumerable<TodoItem> GetAll2()
{
return TodoItems.GetAll();
}
[HttpGet("{id}", Name="GetTodo")]
public IActionResult GetById(string id)
{
var item = TodoItems.Find(id);
if (item == null)
return HttpNotFound();
return new ObjectResult(item);
}
public ITodoRepository TodoItems { get; set; }
}
并调用方法:
http://localhost:5056/api/todo/first
http://localhost:5056/api/todo/second
您可以详细了解 查看全文