0

I'm unable to post JSON object in the body of my HTTP message.

I have even tried this

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

but it still didn't work

Here is my code:

<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    type:<br>
    <input type="number" ng-model="config.type"><br>
    Id:<br>
    <input type="text" ng-model="config.Id">
    <br><br>
    <button ng-click="submit()">Submit</button>
  </form>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http) {
    $scope.config = {type:0, Id:"786"};
    $scope.submit = function() {
        var data = $scope.config;
        //$http.post("http://localhost:8612/api/values/", data);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "http://localhost:8612/api/values/", true);
        xhttp.setRequestHeader("Content-type", "application/json");
        xhttp.send(JSON.stringify(data));
        alert("Done");
    };
});
</script>

</body>
</html>

I am getting an error that is my object is empty in this method

// POST api/values
[HttpPost]
public IActionResult Post([FromBody]object c)

1 Answer 1

2

So the deserialization is failing probably. having the request model as object type is wrong; instead you should define a proper request model and use that rather like

public class ApiRequestModel 
{
   // define all your required properties client going to send
}

[HttpPost]
public IActionResult Post([FromBody] ApiRequestModel c)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.