Gabriel G. Roy
Gabriel G. Roy

Reputation: 2632

Web API custom IContractResolver

I implemented a custom IContractResolver so that I could dynamically filter out certain properties on an object from my Web API. As an example, the action GetEmployees will filter out the "Id" property of each employee returned.

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

The problem is that in the same method, I would like to set the contract resolver back to its default value. Something like this:

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
}

What's the best way to achieve this?

Upvotes: 2

Views: 1446

Answers (1)

It's definitely not the way you try it. You'll run in threading issues this way.

One way could be to alter your returned object to not contain the Id-property. Instead make a more specialized object. This is the way I'd go.

Alternatively you can return a HttpResponseMessage directly and set the content to whatever you like. But then you have to take care of serializing and content negation yourself.

Upvotes: 2

Related Questions