AngularJS $http.post ASP.NET 具有简单类型参数的 Web API 控制器

AngularJS $http.post to ASP.NET Web API controller with simple type argument

本文关键字:类型参数 简单 Web 控制器 API http post ASP NET AngularJS      更新时间:2023-09-26

我有一个简单的测试来尝试理解从AngularJS到 ASP.NET WebAPI的 http.post 美元。帖子设法成功,但 API 上收到的值显示为空。我已经对此进行了测试,并看到$scope对象在发布之前具有值。

我已经检查了各个地方,我看到 WebAPI ASP.NET 以奇怪的方式处理帖子数据。

这是我用于获取输入的HTML代码,基本.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 个简单参数的信息。最后,我还看到我应该将我的帖子值括在引号中或给出一个前导"="符号,但这两种方法似乎都不起作用。任何帮助或建议都会很棒。

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

如果您的控制器接受具有 [FromBody] 属性的基元类型,则它需要在 POST 正文中=value,而不是 JSON。您可以在此处阅读有关该主题的更多信息。

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

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

还要注意双引号是如何连接的,以便子模拟值实际上是"Your Title"的,而不仅仅是Your Title,这将使它成为无效的字符串。

.

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