通过asp.net webapi获得正确的路线2

时间:2014-05-30 14:04:21

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

我正在努力让我的路线开始工作但最终却出错了。

目前这是我唯一的途径:

    config.Routes.MapHttpRoute(
          name: "ActionApi",
          routeTemplate: "api/{controller}/{action}/{id}",
          defaults: new { id = RouteParameter.Optional }
      );

我评论了这个,因为我认为这是问题

   //config.Routes.MapHttpRoute(
    //    name: "DefaultApi",
    //    routeTemplate: "api/{controller}/{id}",
    //    defaults: new { id = RouteParameter.Optional }
    //);

这是我的两种方法:

    public class ProductsController : ApiController
    {
      Product[] products = new Product[] 
      { 
        new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
      };

    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }

    [ActionName("GetAllProducts")]
    public IEnumerable<Product> GetAllProductsAction()
    {
        return products;
    }
  }

尝试在此网址上访问时:http://localhost:27720/api/products/GetAllProducts我收到错误消息:Multiple actions were found that match the request

怎么会这样?我已经使用特定的操作方法命名其中一个。这是设计还是我错误地配置了我的路线?

1 个答案:

答案 0 :(得分:1)

具有public IEnumerable<Product> GetAllProducts()属性的

public IEnumerable<Product> GetAllProductsAction()ActionName("GetAllProducts")肯定会解析为相同的网址,因此发现多个操作符合请求错误。

更改一个的操作名称或另一个的方法名称...或删除其中一个方法,因为它们当前是多余的。

相关问题