0

我在 web api 中有两个或多个 get 方法(如下所示,给出代码 GetProducts 和 GetProductsNew 是 get 方法)。当我使用 Angular js 的 ng-resource 时,每当我尝试调用 get 函数时,它都会给出一个模棱两可的错误。假设我想调用 GetProductsNew 方法,那么我该如何调用?有人可以帮忙吗,在此先感谢:)

    // This is my web api code
    public class ProductController : ApiController
    {
      ...
      public HttpResponseMessage GetProducts()
      { 
      }

      public HttpResponseMessage GetProductsNew()
      {
      }
    }

    // **This is my angular** 

    // This is the code in controller.js, using which i am calling the get method from above code, but here the problem is, since the above web api is having the two gt method, i am getting the "Multiple actions were found that match the request"

    productcatControllers.controller('ProductListCtrl', ['$scope', '$routeParams',
    '$location', '$route', 'productService',
    function ($scope, $routeParams, $location, $route, productService) 
    {
        productService.query(function (data) {
            $scope.products = data;
        });
    }]);

   // This is the service of angular js
   var phonecatServices = angular.module('productcatServices', ['ngResource']);

   phonecatServices.factory("productService", function ($resource) {
       return $resource(
           "/api/Product/:id",
           { id: "@id" },
           {
              "update": { method: "PUT" }

           }
       );
   });
4

1 回答 1

0

通过“模棱两可的错误”,我猜你得到的是:“找到与请求匹配的多个操作......”?这是因为您不能Get在同一个控制器中拥有多个具有相同签名的方法。

尝试将这些属性添加到 webapi 中的方法中

public class ProductController : ApiController
{
  [HttpGet]
  [Route(Name = "GetProducts")]
  public HttpResponseMessage GetProducts()
  { 
  }

  [HttpGet]
  [Route(Name = "GetProductsNew")]
  public HttpResponseMessage GetProductsNew()
  {
  }
}

如果您尚未安装AspNet.WebApi.WebHost ,则需要安装:

Install-Package Microsoft.AspNet.WebApi.WebHost


这篇文章对属性路由 有很好的解释

于 2016-02-20T08:17:56.153 回答