【问题标题】:How does decorating a class with `[Serializable]` attribute makes difference?用 `[Serializable]` 属性装饰一个类有何不同?
【发布时间】:2017-03-20 09:52:58
【问题描述】:

进一步提出我的以下问题,

What is causing the model to null

我花了三个多小时找出原因。作为命中尝试过程的一部分,我从课堂上删除了[Serializable],令人惊讶的模型开始获得价值。

角度服务:-

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 模型时,它的所有值都为空。

我的初始 LoginVM 类

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

以下两次更新解决了我的问题。

1

   //[Serializable] removed this attribute
   public class LoginVM 
   {
   [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }
   }

2

 $http(
   {
       url: "/api/user/login",
       method: "POST",
       data:  user , // directly passed user object to API
       contentType: "application/json"
   })

我想了解用 [Serializable] 属性装饰一个类并直接传递对象有何不同??

如果我需要传递多个参数,那我将如何传递呢??

【问题讨论】:

    标签: c# angularjs serialization asp.net-web-api


    【解决方案1】:

    原因是Web Api对待Serializable属性specifically

    Json.NET 现在检测具有 SerializableAttribute 和 序列化该类型的所有字段,包括公共的和私有的,以及 忽略属性。这在您感兴趣时很有用 在类型上往返数据,而不关心 JSON 的外观 喜欢。

    如果您需要保留 Serializable 属性 - 您可以使用普通的 JsonObject 属性来装饰您的模型:

    [Serializable]
    [JsonObject]
    public class LoginVM 
    {
        [Required]
        public string Username { get; set; }
        [Required]
        public string Password { get; set; }
    }
    

    【讨论】:

    • 往返是什么意思??请加。谢谢
    • 我认为对于您的情况来说重要的部分是当您...时不在乎 JSON 的样子。我已经为我的答案添加了解决方法。
    • 谢谢。我正在浏览共享的链接。
    • @Kgn-web,如果我的回答解决了您的问题 - 请接受。
    • 当然。我会做。我被别的东西占据了。我已完成对链接的阅读,但在我的情况下需要验证。我已对您的回答投了赞成票,并且我将确保在发布后立即接受以正确解决该问题。
    猜你喜欢
    • 2019-10-08
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 2020-11-11
    • 2016-07-30
    • 2020-06-20
    • 1970-01-01
    • 2019-08-19
    相关资源
    最近更新 更多