使用简单类型参数的AngularJS $ http.post到ASP.NET Web API控制器

时间:2016-02-17 22:24:23

标签: javascript c# asp.net angularjs asp.net-web-api

我有一个简单的测试,试图理解从AngularJS到ASP.NET WebAPI的$ http.post。该帖子设法成功,但API上获得的值显示为null。我测试过这个,看到$ scope对象在发布之前保存了一个值。

我已经检查了所有地方,我发现ASP.NET WebAPI以奇怪的方式处理帖子数据。

以下是我获取输入的HTML代码,Basic.html:

<form name="basicItem" novalidate ng-app="app" ng-controller="ItemCtrl">
<label id="titlelabel" class="required">Title</label>
<input ng-model="item.Title" type="text" id="titlefield" name="Title" 
required />

这是来自ItemController.js的代码,它检查验证和帖子(我使用的是CORS,因为这两个程序都有不同的域):

app.controller("ItemCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.submitForm = function (form) {

if (form.$valid) {       //If Title has some value
    item = {
    "Title": $scope.item.Title,     //Set "Title" to the user input
           }
    alert($scope.item.Title);        //This shows that my value is not null
    $http.post("http://localhost:50261",
      {
      testTitle: $scope.item.Title       //!!!Probably the problem, sets 
      }).success(function (result) {     //the parameter of API post
           alert('Success!');            
      }).error(function (data) {
           alert("Valid but didn't connect");
      console.log(data);
      })

这是API控制器中的代码,EntryController.cs:

[HttpPost]
public string CreateEntry([FromBody]string testTitle)
{
     return testTitle; //returns null!!!
}

我已阅读有关需要[FromBody]并仅使用1个简单参数的内容。最后我还看到我应该将我的post值包装在引号中或给出一个前导“=”符号,但这两种方法似乎都不起作用。任何帮助或建议都会很棒。

2 个答案:

答案 0 :(得分:3)

正如 bluetoft 所提到的,问题是WebAPI处理序列化有点奇怪。

如果您的控制器接受具有[FromBody]属性的基本类型,则它在POST主体中需要=value,而不是JSON。您可以阅读more on that topic here

因此,您的请求应仅包含原始值,如下所示:

    $http.post(urlTest, '"' + $scope.item.Title +'"').success(function(result) { 
        alert('Success!');
    }).error(function(data) {
        alert("Error!");
    });

另请注意如何连接双引号,以使subimitted值实际为"Your Title",而不是仅Your Title,这会使其成为无效字符串。

答案 1 :(得分:0)

.NET web api控制器处理序列化有点奇怪。您需要先JSON.stringify您的数据。在你的控制器中试试这个:

 $http.post("http://localhost:50261",
      JSON.stringify({
      testTitle: $scope.item.Title       
      })).success(function (result) {     //the parameter of API post
           alert('Success!');            
      }).error(function (data) {
           alert("Valid but didn't connect");
      console.log(data);
      })