Determining properties to serialize in Json.Net based on user

asp.net-web-api, c#, json.net

Solution

You can create a custom `ContractResolver`

var json = JsonConvert.SerializeObject(
                new UserClass() {ID=666, Name="john", SurName="doe"},
                new JsonSerializerSettings() { ContractResolver = new CustomContractResolver(new[]{"ID", "SurName"}) }
            );

in this example, output json will only include `ID` and `SurName` (not `Name`)

public class UserClass
{
    public int ID { set; get; }
    public string Name {set; get;}
    public string SurName { set; get; }
}

public class CustomContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    IEnumerable<string> _allowedProps = null;

    public CustomContractResolver(IEnumerable<string> allowedProps)
    {
        _allowedProps = allowedProps;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return _allowedProps.Select(p=>new JsonProperty() {
            PropertyName = p,
            PropertyType = type.GetProperty(p).PropertyType,
            Readable = true,
            Writable = true,
            ValueProvider = base.CreateMemberValueProvider(type.GetMember(p).First())
        } ).ToList();
    }
}

Problem

I am creating a ASP MVC Web API. I now want to determine what properties to serialize of a object based on the user that is doing the request. The ApiController knows the user. And based on the user I have a function that returns a string array with the property names the user has rights to on the model. How can I pass the user to the ContractResolver so it only affects the current request and not possible simultanious requests from other users?

Original source