Web API自定义IContractResolver

时间:2013-04-09 12:50:25

标签: c# json.net asp.net-web-api

我实现了一个自定义IContractResolver,以便我可以从Web API动态过滤掉对象的某些属性。例如,GetEmployees操作将过滤掉每个返回的员工的“Id”属性。

public IEnumerable<Employee> GetEmployees()
{
    var ignoreList = new List<string> {"Id"};
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new JsonContractResolver(ignoreList);
    return db.Employees.AsEnumerable();
}

问题在于,在同一方法中,我想将合约解析器设置回其默认值。像这样:

public IEnumerable<Employee> GetEmployees()
{
    var defaultContractResolver = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver;
    var ignoreList = new List<string> {"Id"};
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new JsonContractResolver(ignoreList);
    // Serialize object
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = defaultContractResolver;
    // return serialized object
}

实现这一目标的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

这绝对不是你尝试的方式。你会以这种方式运行线程问题。

一种方法是将您返回的对象更改为不包含Id - 属性。而是制作一个更专业的对象。这就是我的方式。

或者,您可以直接返回HttpResponseMessage并将内容设置为您喜欢的内容。但是你必须自己处理序列化和内容否定。