【问题标题】:Custom Json.NET serializer settings per type每种类型的自定义 Json.NET 序列化程序设置
【发布时间】:2013-07-15 03:05:25
【问题描述】:

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

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;

问题是并非所有设置都适用于我项目中的所有类型。我想为执行多态序列化的特定类型指定自定义 TypeNameHandling 和 Binder 选项。

如何按类型或至少按 ApiController 指定 JsonFormatter.SerializationSettings?

【问题讨论】:

  • 对于基于 apicontroller 的配置,您可以查看 per-controller 配置功能:blogs.msdn.com/b/jmstall/archive/2012/05/11/…。这篇文章很旧,但大部分内容也应该与最新的相关。
  • 我尝试按照您的建议使用 IControllerConfiguration 属性来使用每个控制器的配置。我在 Initialize 函数中为 JsonFormatter 指定的设置实际上被请求重用,并被应用于其他控制器。我只将该属性应用于一个特定的控制器。这似乎是一个错误。

标签: c# asp.net-mvc asp.net-web-api json.net


【解决方案1】:

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

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

【讨论】:

  • 你认为你能指出我正确的方向来使这个论点在每个控制器方法中起作用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多