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?
WriteIndented Property (System. Text. Json) Gets or sets a value that indicates whether JSON should use pretty printing.
Specifies the settings on a JsonSerializer object. Newtonsoft.Json.
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With