【问题标题】:AngularJS $http.post to ASP.NET Web API controller with simple type argumentAngularJS $http.post 到带有简单类型参数的 ASP.NET Web API 控制器
【发布时间】:2016-05-29 21:11:12
【问题描述】:

我有一个简单的测试来尝试理解 $http.post 从 AngularJS 到 ASP.NET WebAPI。帖子成功,但在 API 上收到的值显示为空。我已经对此进行了测试,发现 $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 个简单参数的信息。最后,我还看到我应该将我的帖子值用引号括起来或给出一个前导的“=”符号,但这两种方法似乎都不起作用。任何帮助或建议都会很重要。

【问题讨论】:

  • 您是否尝试过返回硬编码字符串值以隔离 Action 绑定值或客户端中的问题?只需使用return "ThisIsATest" 来验证问题出在哪里并告诉我们结果。

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


【解决方案1】:

正如 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!");
    });

还要注意双引号是如何连接的,所以提交的值实际上是"Your Title",而不是只有Your Title,这会使它成为无效字符串。

【讨论】:

  • 感谢您的成功。我读过需要'=value',但我发现的唯一资源是Jquery。非常感谢。
【解决方案2】:

.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);
      })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多