我正在使用 ApiController,它使用全局 HttpConfiguration 类来指定 JsonFormatter 设置。我可以非常轻松地全局设置序列化设置,如下所示:
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
问题是并非所有设置都适用于我的项目中的所有类型。我想为执行多态序列化的特定类型指定自定义 TypeNameHandling 和 Binder 选项。
如何在宠物类型上或至少在每个 ApiController 的基础上指定 Json Formatter.Serialization 设置?
根据您上面的评论,以下是每个控制器配置的示例:
[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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)