rest web api 2 makes a call to action method without invoked

风格不统一 提交于 2019-12-25 17:57:27

问题


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

回答1:


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().

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

}

And to call the methods:

http://localhost:5056/api/todo/first

http://localhost:5056/api/todo/second

You can read more about it here



来源:https://stackoverflow.com/questions/37608637/rest-web-api-2-makes-a-call-to-action-method-without-invoked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!