是什么导致模型为空 [英] What is causing the model to null

查看:74
本文介绍了是什么导致模型为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular服务:-

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

角度控制器

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
        {

        }
    }

但是当我调试WebAPI模型时,它的所有值都为null.

But when I debug the WebAPI model it has all the values as null.

我的LoginVM类

 [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }

为什么我将属性设置为null?

Why I am getting the properties as null?

推荐答案

您错误地传递了内容类型标头.它作为headers参数的一部分传递,如下所示:

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

并且您不需要在方法上使用 [FromBody] 属性,因为您的 LoginVM 是复杂类型(类).

And you shouldn't need the [FromBody] Attribute on your method because your LoginVM is a complex type (Class).

此外,在过去,Visual Studio有时会播放,并且调试不正确.如果您使用的是IDE,则值得关闭Vi​​sual Studio并重新打开它.

这篇关于是什么导致模型为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆