簡體   English   中英

使用簡單類型參數的AngularJS $ http.post到ASP.NET Web API控制器

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

我有一個簡單的測試,試圖理解從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值包裝在引號中或給出一個前導“=”符號,但這兩種方法似乎都不起作用。 任何幫助或建議都將是盛大的。

正如bluetoft所提到的,問題是WebAPI處理序列化有點奇怪。

如果你的控制器接受帶有[FromBody]屬性的基本類型,它在POST體中需要=value ,而不是JSON。 您可以在此處詳細了解該主題

所以你的請求應該只包含原始值,如下所示:

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

還要注意雙引號是如何連接的,因此subimitted值實際上是"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);
      })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM