how to dynamic jsonignore according to user authorize?

女生的网名这么多〃 提交于 2021-01-27 04:21:10

问题


I use Metadata and JsonIgnore to remove special field from being serializing.

[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; }  
    }  
}  

How can I dynamic control which field should be serialized or not. For some thing like

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; }  
    }  
} 

回答1:


Conditional property serialization




回答2:


JsonIgnore is a property which can't be set dynamically. But you can try something similar like this.

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;
            } 
        }  

    }  
} 

By this way, You can save the default value instead of saving the actual value for a property.



来源:https://stackoverflow.com/questions/16138840/how-to-dynamic-jsonignore-according-to-user-authorize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!