WebApi模型上带有DataAnnotations的Json结果

Json Result with DataAnnotations on Model in WebApi

本文关键字:Json 结果 DataAnnotations 模型 WebApi      更新时间:2023-09-26

我正在使用ASP.NET WebApi,在将结果发送到JSON时,是否可以在Model-ModelMetadata上发送数据注释例如DisplayName属性、ShowInEdit、ShowInDispplay和其他自定义属性以及Fieldnmae和value。

public class Role
    {
        public Role()
        {
            Users = new List<User>();
        }
        [ScafoldingColumn(false)]
        public int RoleId { get; set; }
        [DisplayName("Role Name")]
        [Required]
        [ShowForDisplay(true)]
        [ShowForEdit(true)]
        public string RoleName { get; set; }
        [ShowForDisplay(true)]
        public ICollection<User> Users { get; set; }
    }

提前感谢

JSON作为一种文件格式不支持数据注释。到目前为止,我看到的最好的解决方案是使用元操作。这些元操作可以将数据注释作为附加的json对象返回。之后,您还可以将这些数据缓存在客户端或类似设备的本地存储中,这样您就不需要在每次用户访问页面时下载它们。