Передача параметров: в Web API работает с $ http.get, но не с $ http.Post - PullRequest
0 голосов
/ 25 апреля 2018

AngularJS 1.59

Этот вызов API работает с $http.get.

JS ViewModel

  $scope.placeOrder = function () { //'api/order/create'
    var order = { AccountId : accountId, Amount : $scope.subTotal,
      Tax: $scope.tax, Shipping: $scope.shipping }
    var orderJSON = JSON.stringify(order);
    viewModelHelper.apiGet('api/order/create', { params: { order: orderJSON } },
      function (result) {
        var orderId = result.data;
      });
  }

App.js

self.apiGet = function (uri, data, success, failure, always) {
  self.isLoading = true;
  self.modelIsValid = true;
  $http.get(AlbumApp.rootPath + uri, data)
      .then(function (result) {
        success(result);
        if (always != null)
          always();
        self.isLoading = false;
      }, function (result) {
        if (failure == null) {
          if (result.status != 400)
            self.modelErrors = [result.status + ': ' + result.statusText +
              ' - ' + result.data];
          else
            self.modelErrors = [result.data + ''];
          self.modelIsValid = false;
        }
        else
          failure(result);
        if (always != null)
          always();
        self.isLoading = false;
      });
}

self.apiPost = function (uri, data, success, failure, always) {
  self.isLoading = true;
  self.modelIsValid = true;
  $http.post(AlbumApp.rootPath + uri, data)
      .then(function (result) {
        success(result);
        if (always != null)
          always();
        self.isLoading = false;
      }, function (result) {
        if (failure == null) {
          if (result.status != 400)
            self.modelErrors = [result.status + ': ' + result.statusText + ' - ' + result.data];
          else self.modelErrors = [result.data];
          self.modelIsValid = false;
        }
        else failure(result);
        if (always != null) always();
        self.isLoading = false;
      });
}

APIController

[HttpGet]
[Route("create")]
public IHttpActionResult Create(string order) { 
  var _order = JsonConvert.DeserializeObject<Order>(order); ... }

Но так как это функция Create, я хочу использовать $http.post.Когда я изменяю вызов на

  $scope.placeOrder = function () { //'api/order/create'
    var order = { AccountId : accountId, Amount : $scope.subTotal,
      Tax: $scope.tax, Shipping: $scope.shipping }
    var orderJSON = JSON.stringify(order);
    viewModelHelper.apiPost('api/order/create', { params: { order: orderJSON } },
      //null,
      function (result) {
        var orderId = result.data;
      });
  }

и действие моего контроллера на

[HttpPost]
[Route("create")] 
public IHttpActionResult Create(string order) { 
  var _order = JsonConvert.DeserializeObject<Order>(order); ... }

, я получаю ошибку 404:

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:50597/api/order/create'.
</Message>
<MessageDetail>
No action was found on the controller 'OrderApi' that matches the request.
</MessageDetail>
</Error>

Это ошибка или нетЯ упустил какой-то концептуальный момент или у меня есть ошибка в моем коде?

Решение: (Спасибо Giovani)

params: необходимо передать в config в $http.get и $http.post.Два метода имеют разные подписи.

В apiGet переименованы data в configapiPost добавлено config.

В apiPost добавлен вызов null, поэтому params: передается config, а не data.

приложению.js

self.apiGet = function (uri, config, success, failure, always) {
  self.isLoading = true;
  self.modelIsValid = true;
  $http.get(AlbumApp.rootPath + uri, config)
...

self.apiPost = function (uri, data, config, success, failure, always) {
  self.isLoading = true;
  self.modelIsValid = true;
  $http.post(AlbumApp.rootPath + uri, data, config)

JS ViewModel

  $scope.placeOrder = function () { //'api/order/create'
    var order = { AccountId : accountId, Amount : $scope.subTotal,
      Tax: $scope.tax, Shipping: $scope.shipping }
    var orderJSON = JSON.stringify(order);
    viewModelHelper.apiPost('api/order/create', null, { params: { order: orderJSON } },
      function (result) {
        var orderId = result.data;
      }); }

1 Ответ

0 голосов
/ 25 апреля 2018

$ http.get () и $ http.post () имеют разные сигнатуры метода. подробнее

$http.get(<URL>, <DATA (params, responseType, etc..)>)
$http.post(<URL>, <BODY_DATA>, <DATA (params, responseType, etc..)>
...