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?

Trevor Elliott
  • 11,292
  • 11
  • 63
  • 102
  • 1
    For apicontroller based config, you can take a look at per-controller configuration feature: http://blogs.msdn.com/b/jmstall/archive/2012/05/11/per-controller-configuration-in-webapi.aspx . this post is a old one, but most of the stuff should be relevant for the latest bits too. – Kiran Jul 16 '13 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. – Trevor Elliott Jul 17 '13 at 18:56

1 Answers1

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);
    }
}
Kiran
  • 56,921
  • 15
  • 176
  • 161
  • 1
    Do you think you could point me in the right direction to make this argument work per Controller Method? – WillFM Apr 02 '14 at 20:31