【问题标题】:Angularjs $resource multiple POSTAngularjs $resource 多个 POST
【发布时间】:2015-12-24 02:29:46
【问题描述】:

我有多个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(未找到)

【问题讨论】:

  • 服务器 webapi 控制器上设置的基本路由是什么?你也可以将webapi函数重命名为PostAddToWatchList并尝试。
  • 基础路由是[RoutePrefix("api/Ads")]

标签: javascript .net angularjs asp.net-web-api angular-resource


【解决方案1】:

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

如果参数是“简单”类型,Web API 会尝试获取该值 来自 URI。简单类型包括 .NET 原始类型(int, bool、double 等),以及 TimeSpan、DateTime、Guid、decimal、 和字符串,加上任何带有类型转换器的类型,可以从 一个字符串。 (稍后会详细介绍类型转换器。)对于复杂类型,Web API 尝试使用媒体类型从消息正文中读取值 格式化程序。 More on this..

你有几个选择:

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

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

2 - 显然使用一个复杂的对象,就像你在第一种方法中所做的那样。尽管拥有一个具有单个 int 属性的类感觉很愚蠢……这就是为什么你我都不喜欢这种方法的原因。但是,如果您已经有一个 Ad 类,那么重用它并没有错。


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

=123

【讨论】:

    猜你喜欢
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多