简体   繁体   中英

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

I have a simple test to try to understand $http.post from AngularJS to ASP.NET WebAPI. The post manages to succeed, but received value on the API appears as null. I have tested this and seen that the $scope object holds a value before being posted.

I have checked all over the place and I see that ASP.NET WebAPI handles posts data in strange ways.

Here is my HTML code for getting the input, 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 />

This is the code from ItemController.js, which checks validation and posts (I am using CORS since both of these programs have separate domains):

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

And this is the code in the API controller, EntryController.cs:

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

I have read about needing [FromBody] and only using 1 simple parameter. Finally I have also seen that I should wrap my post value in quotes or give a leading "=" sign, but both of these methods don't seem to work. Any help or suggestions would be grand.

As mentioned by bluetoft , the problem is that WebAPI handles the serialization a little strange.

If your controller accepts a primitive type with [FromBody] attribute, it expects =value in POST body, instead of JSON. You can read more on that topic here .

So your request should contain only the primitive value, like this:

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

Also note how double quotes are concatenated, so that the subimitted value is actually "Your Title" , instead of only Your Title , which would make it invalid string.

.NET web api controllers handle the serialization a little strange. You'll need to JSON.stringify your data first. Try this in your controller:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM