Angularjs $资源倍数 POST

Angularjs $resource multiple POST

我有多个 Web Api Post methods 喜欢:

    [HttpPost]
    public async Task<IHttpActionResult> Post([FromBody] AdModel adModel)
    {
        //Post
    }

    [HttpPost]
    [Route("AddToWatchList")]
    public async Task<IHttpActionResult> AddToWatchList(int adId)
    {
        // Post to database
    }

这是我的 AngularJs 服务器:

app.factory('adService', ['$resource', 'ngAuthSettings', function ($resource, ngAuthSettings) {

      var serviceBase = ngAuthSettings.apiServiceBaseUri;

return $resource(serviceBase + 'api/Ads/', {}, {
            addToWatchList: {
            method: 'POST',
            url: serviceBase + 'api/Ads/addToWatchList'
           }
        }
    });
}]);

AngularJs 控制器:

app.controller('listCategoryAdsController',
    ['ngAuthSettings', '$scope', 'adService', '$routeParams', '$location',
    function (ngAuthSettings, $scope, adService, $routeParams, $location) {

    $scope.addToWatchlist = function (adId) {
        adService.addToWatchList({ adId: adId }).$promise.then(
            function(result) {
                var path = $location.path();
                $location.path(path).search('nw', 1);
            },
            function (error) {

        });
    };

我的 Html 从哪里调用方法:

<div class="col-sm-3 text-right price-box" data-ng-repeat="ad in Ads">
     <h2 class="item-price">
         $ {{ad.price}}
     </h2>
     <i class="fa fa-certificate">
     </i>
     <a ng-click="addToWatchlist(ad.adId)" class="btn btn-default  btn-sm make-favorite" tooltip="Click to add to watch list"
           tooltip-placement="left"
           tooltip-trigger="mouseenter">
          <i class="fa fa-heart"></i>
           <span>Watch list</span>
     </a>
</div>

我的问题是 Post([FromBody] AdModel adModel) 被完美调用。但是当我打电话给 AddToWatchList(int adId) 时,我得到:

POST http://localhost:8081/api/Ads/addToWatchList 404 (Not Found)

您正在向 AddToWatchList() 发送一个简单类型 (int),因此 Web API 正在 URI 中查找 adId 参数。

If the parameter is a “simple” type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.) For complex types, Web API tries to read the value from the message body, using a media-type formatter. More on this..

您有几个选择:

1 - 通过 URI 发送 adId...api/ads/addtowatchlist?adId=123

$resource(serviceBase + 'api/Ads/addToWatchList', { }, {
    addToWatchList: { method:'POST', params:{ adId:adId } }
});

2 - 显然使用第一种方法中的复杂对象。尽管用一个 class 和一个 int 属性 感觉很傻……这就是你我不喜欢这种方法的原因。但是,如果您已经有一个广告 class,重复使用它没有错。


3 - 尝试 this solution,这需要您将 [FromBody] 添加到您的 int 参数中。并发送没有标识符的 adId

=123