以编程方式在.NET EF Code First上打开属性序列化

时间:2015-12-11 04:41:44

标签: c# asp.net entity-framework asp.net-web-api asp.net-web-api2

我在EF 6上使用CodeFirst建模我的数据。 我正在构建一个不同类型的客户端可以访问的Web API,但根据客户端的配置,他们应该看到或不知道模型的某些属性。

¿如何开启或关闭[JsonIgnore][serialized]?是否可以设置一组规则来执行此操作,如验证器?

1 个答案:

答案 0 :(得分:1)

选项1:使用自定义ContractResolver

您可以创建自定义合约解析程序并在创建响应时使用它:

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

选项2:使用词典

您可以使用逗号分隔的属性名称字符串来忽略,然后选择属性并将它们(名称和值)放在字典中并将其用作结果:

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