【问题标题】:rest web api 2 makes a call to action method without invokedrest web api 2 在没有调用的情况下调用操作方法
【发布时间】:2016-06-03 07:38:28
【问题描述】:

我正在关注位于此处的教程:https://docs.asp.net/en/latest/tutorials/first-web-api.html 我在 iis express 中运行 web api,并使用 postman 调用它,路径如下: http://localhost:5056/api/todo 此调用命中构造函数,然后以某种方式调用 GetAll 函数从未被调用,甚至没有 HttpGet 动词。 如何调用?

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

【问题讨论】:

  • 一些代码可能会有所帮助
  • 用代码更新了问题。我不明白为什么要投反对票。我试图理解一些事情。诚实的问题。

标签: c# rest asp.net-web-api2


【解决方案1】:

控制器中的所有方法都是默认的 HttpGet。您不需要显式指定 HttpGet 动词。 如果您使用 WebApiConfig 中指定的默认路由并调用http://localhost:5056/api/todo,它将路由到控制器中的第一个无参数函数。在你的情况下 GetAll()。

如果要指定路由,可以使用属性 RoutePreFix 和 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

你可以阅读更多关于它here

【讨论】:

  • 如果你有两种方法呢?它如何选择哪一个?
猜你喜欢
  • 2020-05-03
  • 2013-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
相关资源
最近更新 更多