【问题标题】:how to dynamic jsonignore according to user authorize?如何根据用户授权动态jsonignore?
【发布时间】:2013-04-22 03:10:30
【问题描述】:

我使用 Metadata 和 JsonIgnore 从序列化中删除特殊字段。

[Authorize(Roles = "admin")]
public class UserController : ApiController
{
    public IEnumerable<user> Get()
    {
        using (var mydb = new ModelContainer())
        {
            return mydb.userSet.ToList();
        }
    }
}

[MetadataType(typeof(user_Metadata))]  
public partial class user
{  
    private class user_Metadata  
    {  
        [JsonIgnore]  
        public virtual password { get; set; }  

        public virtual adminFile { get; set; }  
    }  
}  

我怎样才能动态控制哪个字段应该被序列化。对于一些像

public partial class user
{  
    private class user_Metadata  
    {  
        [JsonIgnore]  
        public virtual password { get; set; }  
        [Roes == admin?JsonIgnore:JsonNotIgnore] //some thing like this
        public virtual adminFile { get; set; }  
    }  
} 

【问题讨论】:

    标签: json.net asp.net-web-api


    【解决方案1】:

    【讨论】:

    • @JamesNK,谢谢,“条件”是我应该搜索的关键词。
    【解决方案2】:

    JsonIgnore 是一个不能动态设置的属性。但是您可以尝试类似的方法。

    public partial class user
    {  
        private class user_Metadata  
        {  
            [JsonIgnore]  
            public virtual password { get; set; }  
    
            //[Roes == admin?JsonIgnore:JsonNotIgnore] //something like this
            public virtual adminFile 
            { 
                get
                {
                   if(Roes == admin)
                       return NULL;
                   else
                       return adminFile;
                }
                set
                {
                   if(Roes == admin)
                       value = NULL;
                   else
                       value = adminFile;
                } 
            }  
    
        }  
    } 
    

    通过这种方式,您可以保存默认值而不是保存属性的实际值。

    【讨论】:

    • 谢谢,这可以让事情顺利进行。但我想像詹姆斯所说的那样在 json.net 中使用
    猜你喜欢
    • 2014-06-25
    • 2020-06-08
    • 1970-01-01
    • 2020-02-05
    • 2019-05-12
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    相关资源
    最近更新 更多