【问题标题】:Programatically turn on properties serialization on .NET EF Code First以编程方式在 .NET EF Code First 中打开属性序列化
【发布时间】:2015-12-11 04:41:44
【问题描述】:

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

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

【问题讨论】:

  • 如何获得模型的 json 表示?
  • JsonMediaTypeFormatter config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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


【解决方案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"}

【讨论】:

  • 我正在考虑一种使用数据注释的方法,但我认为使用序列化到用户声明中的排除属性对象,然后将其作为字符串传递给合同将是一个更清洁的解决方案。我忘记了存在诸如contractResolver之类的东西。谢谢。
  • 完成。再次感谢:D
猜你喜欢
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多