V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xcaptain
V2EX  ›  .NET

如何通过 model binding 来解析嵌套的 json 请求体

  •  
  •   xcaptain · 2019-04-10 17:16:33 +08:00 · 3087 次点击
    这是一个创建于 1814 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如说我想向服务器 post 一个请求,请求体如下:

    {"code": "code1", "userInfo":{"nickName": "joey", "gender": 1}}
    

    写了一个自定义的 model

    public class LoginModel
    {
        [BindRequired]
        [JsonProperty(PropertyName = "code")]
        public string code { get; set; }
    
        [BindRequired]
        [JsonProperty(PropertyName = "userInfo")]
        public UserInfo userInfo { get; set; }
    }
    public class UserInfo
    {
        public string nickName { get; }
    
        public int gender { get; }
    }
    

    在 controller 中能正确获取到 code 的值,但是 userInfo 这个字段总是 null,是框架没法识别嵌套的userInfo属性,还是没法根据我传入的 json 自动生成UserInfo对象呢?我目前做了个 hack 就是把 userInfo 的字段类型改为Dictionary<string, string>之后能读到数据,但是感觉这不是好办法,还是想能自动根据请求构造 UserInfo

    3 条回复    2019-07-06 08:50:44 +08:00
    xcaptain
        1
    xcaptain  
    OP
       2019-04-10 17:18:34 +08:00
    这个版块人好少啊,再求一个人气旺的 .net 论坛网址
    xcaptain
        2
    xcaptain  
    OP
       2019-04-10 18:18:59 +08:00
    上面的问题解决了,是我没有给 UserInfo 这个类的属性加上 set 方法。另外再反馈一个 efcore 好几年都没做的功能 https://github.com/aspnet/EntityFrameworkCore/issues/703
    ragnaroks
        3
    ragnaroks  
       2019-07-06 08:50:44 +08:00
    一是.net 用的人不如 java 多.
    二是很多问题都有完整的解决方案,也不需要提问,至少不用第三方的情况下 MSDN 可以解决你的所有问题.
    你不知道{get;set;}具体做用的话,直接"public Int32 v1;"更合适.
    所谓人气旺,不如看看 stackoverflow.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3080 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:44 · PVG 20:44 · LAX 05:44 · JFK 08:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.