我在EF 6上使用CodeFirst建模我的数据。 我正在构建一个不同类型的客户端可以访问的Web API,但根据客户端的配置,他们应该看到或不知道模型的某些属性。
¿如何开启或关闭[JsonIgnore]
或[serialized]
?是否可以设置一组规则来执行此操作,如验证器?
答案 0 :(得分:1)
您可以创建自定义合约解析程序并在创建响应时使用它:
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);
}
}
这是用法:
[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;
}
结果将是:
{"Id":1,"LastName":"y"}
您可以使用逗号分隔的属性名称字符串来忽略,然后选择属性并将它们(名称和值)放在字典中并将其用作结果:
[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;
}
结果将是:
{"Id":1,"LastName":"y"}