【问题标题】:Multiple actions were found that match the request?找到与请求匹配的多个操作?
【发布时间】:2017-01-07 06:59:59
【问题描述】:

我是 WebAPI 的新手,只是在探索它的默认示例“值”控制器,它与项目一起开箱即用。

我看到它已经有两个 Get 方法:

      // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

我尝试使用复杂类型更改 int id 并收到“找到与请求匹配的多个操作

为什么它之前工作正常?

我的路线是defuatl:

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

我正在使用 Get 方法在 body 中传递一个复杂对象,我知道这不是 Restful 方式,但请帮助我理解它。

非常感谢。

【问题讨论】:

  • 为什么要将复杂对象传递给 GET 方法?你想做什么?
  • 你可以,但是你需要映射那个对象是什么,比如 Get (ObjectType thing)
  • 因为 GET 方法从请求 url 的查询字符串中读取数据。您可以通过查询字符串发送多少数据是有限制的。另一方面,POST 请求从请求正文中读取数据,您可以在其中发送任何内容
  • 你为什么不使用 HttpPost 方法?它们是为此用例创建的。
  • 有点大的话题,但这里有一些关于路由如何工作的事情,这是您问题asp.net/web-api/overview/web-api-routing-and-actions的基础知识

标签: asp.net-mvc asp.net-web-api asp.net-web-api2


【解决方案1】:

您可以为此问题使用ActionName 注释。例如使用:

 [ActionName("IEnumerableGet")]
 public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

所以你可以调用IEnumerableGet 来调用这个方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2017-10-26
    • 2016-10-18
    相关资源
    最近更新 更多