What is causing the model to null

2019-07-30 07:49发布

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?

1条回答
The star\"
2楼-- · 2019-07-30 08:16

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.

查看更多
登录 后发表回答