I have the following class:
public class SomeArg
{
public int name { get; set; }
}
the POST request sends that data
var requestData = {};
requestData.items = [{ name: 1 }, { name: 2 }];
requestData.logic = "and";
$http.post('SomeAction/',
JSON.stringify(requestData),
{ headers: { 'Content-Type': 'application/json' } }
)
.success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
});
and the WebApi controller's action
[HttPost]
public HttpResponseMessage SomeAction(string logic = null,
[FromUri]
SomeArg[] items = null) { ... }
I can see that all of the arguments are null. Why ?
The API controller POST method should look like this
[HttPost]
public HttpResponseMessage SomeAction(string logic = null,
[FromBody]SomeArg[] items = null) { ... }
And the angular call should not serialize the object. Angular will do it.
$http.post('SomeAction/',
requestData,
{ headers: { 'Content-Type': 'application/json' } }
)
.success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
});
Update: I rechecked item passed to server, i think you should create a single object on the server that encapsulates the data being passed in POST such as
public class ActionData {
public string logic {get;set;}
public SomeArg[] items {get;set;}
}
and use this as a single argument to your Web API function
public HttpResponseMessage SomeAction(ActionData data) { ... }
Please read how parameter binding works in webapi http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Related
Angular Service:-
app.service('loginService', ['$http', function ($http) {
this.userLogin = function (user) {
console.log(user); //prints {'username': 'username#gmail.com', 'password': 123'}
$http(
{
url: "/api/user/login",
method: "POST",
data: { 'model': user },
contentType: "application/json"
})
.then(function (data) {
if (data.status.toLower() === "success") {
return data;
}
else {
return null;
}
});
}
Angular Controller
app.controller('homeCtrl', ['$scope', 'loginService', function ($scope, loginService) {
$scope.login = function (user) {
debugger;
console.log($scope.user);
var data = loginService.userLogin($scope.user);
}
}]);
WebAPI.
[Route("api/user/login")]
public void Post([FromBody]LoginVM model)
{
if(ModelState.IsValid)
{
}
else
{
}
}
But when I debug the WebAPI model it has all the values as null.
My LoginVM class
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
Why I am getting the properties as null?
Your passing your content type header incorrectly. It get's passed as part of the headers parameter like so:
$http({
url: "/api/user/login",
method: "POST",
data: { 'model': user },
headers: {
"Content-Type": "application/json"
}
}).then(function (data) {
if (data.status.toLower() === "success") {
return data;
} else {
return null;
}
});
However, unless you have changed the default headers you don't even need to pass the content type. See the default headers in the documentation.
So you can simply make your request like so:
$http({
url: "/api/user/login",
method: "POST",
data: {
model: user
}
}).then(function (data) {
if (data.status.toLower() === "success") {
return data;
} else {
return null;
}
});
And you shouldn't need the [FromBody] Attribute on your method because your LoginVM is a complex type (Class).
Also, I've had it in the past where sometimes visual studio plays up and it's not debugging correctly. It's worth closing visual studio and re-opening it if that's the IDE you're using.
I'm learning AngularJS and Spring MVC. I'm stuck in a situation where I have an angularjs controller from which I do a REST API call to a spring service. I would like to know how to accept those JSON values inside the controller and map to the Model (getters and setters).
I'm doing some validations on the spring side before doing an insert in the database. I would also like to know how to return those error messages to angula JS and populate them on the screen.
This is my AngularJS controller:
var myapp = angular.module("app");
myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
$scope.addconfig = function() {
var dataobj = {
escfirstname : $scope.escfirstname ,esclastname:$scope.esclastname,escage:$scope.escage
}
$http({
url: "http://localhost:8080/services/AddConfig",
method: "POST",
data: dataobj,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
}
});
This is my Spring service:
#Controller
public class TestController {
#RequestMapping(value = "/AddConfig", method = RequestMethod.POST)
public #ResponseBody String PostService(#RequestBody Config person) {
System.out.println("came insidee");
return null;
}
}
I'm able to print the sysout. Now I would like to know how to proceed with this.
enter link description here
like this.
var myapp = angular.module("app");
myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
$scope.addconfig = function() {
var dataObject = {
escfirstname : $scope.escfirstname,
esclastname : $scope.esclastname,
escage : $scope.escage
};
$http({
method: 'POST',
url: 'http://localhost/jsonURL',
data: dataObject,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}).success(function(data, status, headers, config) {
if( data ) {
}
else {
}
}).error(function(data, status, headers, config) {
console.log(status);
});
}
});
#Controller
public class TestController {
#RequestMapping(value = "/AddConfig", method = RequestMethod.POST)
public #ResponseBody String PostService(#RequestBody Config person) {
// System.out.println("person" + person.);
return null;
}
}
I am trying to Post an object from AngularJS to a MVC 5 WebApi Controller, but the value is always null
I can see in Chrome dev tools that the data can be found on the request.
Angular Controller:
$scope.join = function () {
if (!$scope.joinForm.$valid) return;
// Writing it to the server
var payload = $scope.user;
var res = $http.post('/api/some', JSON.stringify( { Data: { payload } }), { header: { 'Content-Type': 'application/json' } });
res.success(function (data, status, headers, config) {
$scope.message = data;
});
res.error(function (data, status, headers, config) {
alert("failure message: " + JSON.stringify({ data: data }));
});
}
MVC 5 API Controller:
public class SomeController : ApiController
{
// POST api/values
public void Post([FromBody]string value)
{
Trace.Write(value);
}
}
If I wrap my object in {Data: {payload}}
{"Data":{"payload":{"symbol":"xxx","amount":12000,"startdate":"2014-05-23T14:26:54.106Z","enddate":"2015-05-23T14:26:54.106Z","interval":"7 minutes"}}}
if I dont wrap it I get:
{"symbol":"xxx","amount":12000,"startdate":"2014-05-23T14:26:54.106Z","enddate":"2015-05-23T14:26:54.106Z","interval":"7 minutes"}
(Visual Studio 2015 is configured to use IISExpress)
Any ideas?
The reason value was null is because the framework's model binder was unable to match the parameter to the data that was sent in the body of the post.
Create a class to store your payload
public class User
{
public string symbol { get; set; }
public int amount { get; set; }
public DateTime startdate { get; set; }
public DateTime enddate { get; set; }
public string interval { get; set; }
}
update controller
public class SomeController : ApiController
{
// POST api/post
public void Post(User user)
{
//consume data
}
}
Angular controller
$scope.join = function () {
if (!$scope.joinForm.$valid) return;
// Writing it to the server
var res = $http.post('/api/some', $scope.user, { header: { 'Content-Type': 'application/json' } });
res.success(function (data, status, headers, config) {
$scope.message = data;
});
res.error(function (data, status, headers, config) {
alert("failure message: " + JSON.stringify({ data: data }));
});
}
Below is my angular and Web APi Code.In the post method null is getting passed instead of India
Angular Code:
HWApp.controller('TestCtrl', function ($scope, $http) {
$scope.SendData = function (Data)
{
$scope.whoo = Data;
console.log(Data);
$http({
url: "api/call/firstCall",
dataType: 'json',
method: 'POST',
data: "India",
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.whoo = response;
})
.error(function (error) {
alert(error);
});
}
}
);
Web Api Controller
public class CallController : ApiController
{
[HttpGet]
public string firstCallGet( )
{
return "Get";
}
[HttpPost]
public string firstCall([FromBody] string a)
{
return a;
}
}
Your data parameter should be JSON object.
data :{country : "India" }
Define a model class to automatically deserialze into.
Public class CountryViewModel{
Public string Country{get; set;}
}
Web Api controller should be as follows
public class CallController : ApiController
{
[HttpPost]
public string FirstCall( CountryViewModel in)
{
return in.Country;
}
}
I have one application consist of ASP.Net WebAPI 2 and Web project for which angularJS is used. The Problem is when i call API with parameters, it does not hit. and when send object, it gets hit.
anjularJS Code:
with parameters
$http({
cache: false
, method: 'POST'
, url: 'http://localhost:51341/api/User/UpdateUser'
, data: { userId: $scope.UsersId, fullName: $scope.name }
}).success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});
Webapi Code
[HttpPost]
public ApiResponse UpdateUser(int userId, string fullName)
{
return this.Response(true, MessageTypes.Success, "User has been saved successfully.");
}
with object
var model = { userId: $scope.UsersId, fullName: $scope.name };
$http({
cache: false
, method: 'POST'
, url: 'http://localhost:51341/api/User/UpdateUser'
, data: model
}).success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});
webapi code
[HttpPost]
public ApiResponse UpdateUser(User model)
{
return this.Response(true, MessageTypes.Success, "User has been saved successfully.");
}
User class
public class User
{
public int UserId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
}
when call made with parameters, api DOES NOT get hit. but When call made with Object, api GETS hit.
What I missed when call made with parameters ? Help will be truly appreciated.
From WebApi docs:
At most one parameter is allowed to read from the message body. So
this will not work:
// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
For other info I suggest to read:
https://damienbod.wordpress.com/2014/08/22/web-api-2-exploring-parameter-binding/
https://stackoverflow.com/a/24629106/3316654