Tre*_*ott 10 c# asp.net-mvc json.net asp.net-web-api
我正在使用ApiController,它使用全局HttpConfiguration类来指定JsonFormatter设置.我可以非常容易地全局设置序列化设置:
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
Run Code Online (Sandbox Code Playgroud)
问题是并非所有设置都适用于我的项目中的所有类型.我想为执行多态序列化的特定类型指定自定义TypeNameHandling和Binder选项.
如何在每个类型上指定JsonFormatter.SerializationSettings,或者在每个ApiController的基础上指定最少?
Kir*_*lla 13
根据您上面的评论,以下是每个控制器配置的示例:
[MyControllerConfig]
public class ValuesController : ApiController
Run Code Online (Sandbox Code Playgroud)
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4214 次 |
| 最近记录: |