如何通过Angular向ASP.net web API发送发布请求

问题描述:

我对angular web和ASP.NET web API都很陌生。在角度我从表单获取值,并尝试通过发布请求将其传递给服务器,她是angular的代码。如何通过Angular向ASP.net web API发送发布请求

app.controller('AddTrnController',['$scope', 'CategoriesService','$http', function($scope, CategoriesService, $http){ 
    $scope.categories =[{}]; 
    $scope.AddTrn = {}; 
    function init(){ 
      CategoriesService.getCategories("1") 
      .success(function(data){ 
       $scope.categories = data; 
      }) 
      .error(function(data, status, headers){alert(status);}); 
     } 
    init(); 

    $scope.change= function(option){ 
     $scope.AddTrn.TrnID = option.CatID; 
     $scope.AddTrn.TrnAccount = 1; 
    }; 


    $scope.UpdateTrans=function(){ 
     alert("21312"); 
     $http({method:"post", 
      url:'http://localhost:18678/api/Transaction', 
      params:"data:$scope.AddTrn"} 
      ).success(function(){alert("succeeded"); 
     }).error(function(){alert("faild");}); 
    }; 

}]); 

她是web API的代码。

public HttpResponseMessage PostTransaction(String transaction) 
     { 
      if (ModelState.IsValid) 
      { 
       HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, transaction); 
       response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = transaction})); 
       return response; 
      } 
      else 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest); 
      } 
     } 

我总是从钓鱼者得到失败的响应,当我在API中创建断点时,它不会触发。

您正在使用params选项将项添加到查询字符串,你可能会想使用的数据选项,而不是一个帖子,请尝试更改代码如下:

$scope.UpdateTrans=function(){ 
     alert("21312"); 
     $http({method:"post", 
       url:'http://localhost:18678/api/Transaction', 
       data:$scope.AddTrn 
       } 
      ).success(function(){alert("succeeded"); 
     }).error(function(){alert("faild");}); 
    }; 
+0

我想双方的他们和我得到相同的结果 – MohamedAbbas

+0

@ user2918388你可以在你的浏览器中使用开发工具,并转到网络选项卡,并粘贴你从请求中获得的响应?如果你告诉我你正在使用什么浏览器,我可以告诉你如何到达 – MDiesel

+0

我正在使用chrome – MohamedAbbas