问题
I have my data modeled with CodeFirst on EF 6. I'm building a Web API to which different type of clients would have access but depending on the client´s configuration they should see or not certain properties of the models.
¿How do I turn on or off the [JsonIgnore]
or [serialized]
? Is it possible to set a certain set of rules to do this, like a validator?
回答1:
Option 1: Using a custom ContractResolver
You can create a custom contract resolver and use it when creating the response:
public class TestContractResolver : DefaultContractResolver
{
public string ExcludeProperties { get; set; }
protected override IList<JsonProperty> CreateProperties(Type type,
MemberSerialization memberSerialization)
{
if (!string.IsNullOrEmpty(ExcludeProperties))
return base.CreateProperties(type, memberSerialization)
.Where(x => !ExcludeProperties.Split(',').Contains(x.PropertyName))
.ToList();
return base.CreateProperties(type, memberSerialization);
}
}
here is the usage:
[HttpGet]
public HttpResponseMessage Test()
{
var person = new Person() { Id = 1, FirstName = "x", LastName = "y", Age = 20 };
string excludeProperties= "FirstName,Age";
string result = JsonConvert.SerializeObject(person, Formatting.None,
new JsonSerializerSettings
{
ContractResolver = new TestContractResolver()
{
ExcludeProperties = excludeProperties
}
});
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(result, Encoding.UTF8, "application/json");
return response;
}
And the result would be:
{"Id":1,"LastName":"y"}
Option 2: Using Dictionary
You can have a comma separated string of property names to ignore, then select properties and put them (name and value) in a dictionary and use them as result:
[HttpGet]
public Dictionary<string, Object> Test()
{
var person = new Person() { Id = 1, FirstName = "x", LastName = "y", Age = 20 };
string excludeProperties = "FirstName,Age";
var dictionary = new Dictionary<string, Object>();
person.GetType().GetProperties()
.Where(x => !excludeProperties.Split(',').Contains(x.Name)).ToList()
.ForEach(p =>
{
var key = p.Name;
var value = p.GetValue(person);
dictionary.Add(key, value);
});
return dictionary;
}
And the result would be:
{"Id":1,"LastName":"y"}
来源:https://stackoverflow.com/questions/34216252/programatically-turn-on-properties-serialization-on-net-ef-code-first