I just went through the pains of figuring that out myself and I needed one that works per-request. You can use that approach and just return the same media formatter. I found setting a formatter on GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver
a bit unreliable for per-request needs, even though I tried handling the per-request needs in one single instance of that class. You can, however try setting your ContractResolver instance there, somewhere in App_Start code
I ended up creating a custom JsonMediaTypeFormatter
that checks if there is a configured ContractResolver for the request, you can just return one and the same resolver:
public class DynamicJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
{
// shown is getting the current formatter, but you can return an instance you prefer
var formatter = base.GetPerRequestFormatterInstance(type, request, mediaType) as JsonMediaTypeFormatter;
// Here I had more code to get the resolver based on request, skipped
((JsonMediaTypeFormatter)formatter).SerializerSettings.ContractResolver = <YourContractResolverInstance>;
return formatter;
}
}
I presume you've figured that part out already but your contract resolver can override `CreateProperties' and have your own logic decide what json properties will be present and what names will they use (added for completeness and benefit of other readers):
public class DynamicContractResolver : DefaultContractResolver
{
...
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization){
...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…