每种类型的自定义Json.NET序列化器设置

10

我正在使用一个ApiController,它使用全局的HttpConfiguration类来指定JsonFormatter的设置。我可以很容易地全局设置序列化设置,如下所示:

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
问题在于我的项目中并非所有设置都适用于所有类型。我想为执行多态序列化的特定类型指定自定义的TypeNameHandling和Binder选项。
我该如何针对每个类型或至少每个ApiController指定JsonFormatter.SerializationSettings?

1
对于基于apicontroller的配置,您可以查看每个控制器配置功能:http://blogs.msdn.com/b/jmstall/archive/2012/05/11/per-controller-configuration-in-webapi.aspx。这篇文章是旧的,但大部分内容应该也适用于最新版本。 - Kiran
我尝试按照你的建议使用IControllerConfiguration属性进行每个控制器的配置。在JsonFormatter的Initialize函数中指定的设置实际上被请求重复使用,并应用于其他控制器。我只将该属性应用于一个特定的控制器。这似乎是一个错误。 - Trevor Elliott
1个回答

14

根据您上面的评论,以下是每个控制器配置的示例:

[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);
    }
}

1
你觉得你能指导我如何使这个参数在控制器方法中起作用吗? - WillFM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接