rest web api 2 makes a call to action method witho

2019-09-19 15:44发布

问题:

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