且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每种类型的自定义Json.NET串行设置

更新时间:2023-02-17 21:08:12

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

Based on your comment above, following is an example of per-controller configuration:

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