[英]Custom Json.NET serializer settings per type
我正在使用ApiController,它使用全局HttpConfiguration類來指定JsonFormatter設置。 我可以非常容易地全局設置序列化設置:
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
問題是並非所有設置都適用於我的項目中的所有類型。 我想為執行多態序列化的特定類型指定自定義TypeNameHandling和Binder選項。
如何在每個類型上指定JsonFormatter.SerializationSettings,或者在每個ApiController的基礎上指定最少?
根據您上面的評論,以下是每個控制器配置的示例:
[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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.