【问题标题】:Child of entity type is null while posting to Web Api发布到 Web Api 时,实体类型的子级为空
【发布时间】:2019-09-23 11:07:49
【问题描述】:

我正在尝试将 Json 发布到 web api

  {
      "Name" :"Irfan",
      "Roles":[
        {"RoleID" : 1}
    ,
     {"RoleID" : 2}]
    }

在 web api 我有这样的模型

public class Role
{
    public Int32 ID { get; set; }
    public Int32? RoleID { get; set; }
    public Int32? UserID { get; set; }
}

public class User
{
    public string Name { get; set; }
    public List<Role> Roles { get; set; }
}

我得到“名称”值,但“角色”为空。如何获得“角色”?

【问题讨论】:

  • 您没有获得角色值,这只是因为在角色类中“ID”列不可为空,您可以使其为空或在 json 对象中传递“ID”的值

标签: json asp.net-core-webapi


【解决方案1】:

请参考以下测试时有效的代码示例:

[Route("test")]
public ActionResult<IEnumerable<string>> test(User user)
{
    return new string[] { "value1", "value2" };
}

请求会喜欢:

POST  https://localhost:XXXX/api/values/test
Content-Type: application/json


{"Name" :"Irfan","Roles":[{"RoleID" : 1},{"RoleID" : 2}]}

使用 Fiddler/Postman 检查您的请求,.NET Core 将帮助自动将 json 映射到服务器端的对象。

【讨论】:

  • 感谢您的回复。问题就在我这边。我没有为 List Roles { get; 使用“公共”访问说明符放; }
  • 好的,我看到你的更新了。这样您就应该回答自己的问题,而不是在没有解释的情况下更新问题。
【解决方案2】:

在构造函数中创建角色对象

public class User
{
     public User()
     {
         this.Roles = new List<Role>();
     }
     public string Name { get; set; }
     public List<Role> Roles { get; set; }
}

【讨论】:

  • 您没有获得角色值,这只是因为在角色类中“ID”列不可为空,您可以使其为空或在 json 对象中传递“ID”的值
猜你喜欢
  • 2013-12-06
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
相关资源
最近更新 更多