10

I am using an ApiController which uses the global HttpConfiguration class to specify the JsonFormatter settings. I can globally set serialization settings as follows very easily:

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects; 

The problem is that not all settings apply to all types in my project. I want to specify custom TypeNameHandling and Binder options for specific types that perform polymorphic serialization.

How can I specify JsonFormatter.SerializationSettings on a per-type or at the least on a per-ApiController basis?

2
  • 1
    For apicontroller based config, you can take a look at per-controller configuration feature: blogs.msdn.com/b/jmstall/archive/2012/05/11/… . this post is a old one, but most of the stuff should be relevant for the latest bits too. Commented Jul 16, 2013 at 19:19
  • I tried resorting to per-controller configuration using the IControllerConfiguration attribute like you have suggested. The settings I am specifying in the Initialize function for the JsonFormatter are actually being re-used by requests and are being applied to other controllers. I only applied the attribute to one particular controller. This seems like a bug. Commented Jul 17, 2013 at 18:56

1 Answer 1

14

Based on your comment above, following is an example of per-controller configuration:

[MyControllerConfig] public class ValuesController : ApiController 

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class MyControllerConfigAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { //remove the existing Json formatter as this is the global formatter and changing any setting on it //would effect other controllers too. controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter); JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter(); formatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All; controllerSettings.Formatters.Insert(0, formatter); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Do you think you could point me in the right direction to make this argument work per Controller Method?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.