我实现了一个自定义的 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
}
实现这一目标的最佳方法是什么?