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:
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:
And you shouldn't need the
[FromBody]
Attribute on your method because yourLoginVM
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.