问题
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