2013-07-16 26 views
10

我正在使用ApiController,它使用全局HttpConfiguration類來指定JsonFormatter設置。每種類型的自定義Json.NET串行器設置

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。這篇文章是一箇舊的,但大多數的東西也應該與最新的位相關。 –

+0

我嘗試使用IControllerConfiguration屬性來執行每個控制器配置,就像您建議的那樣。我在JsonFormatter的Initialize函數中指定的設置實際上被請求重用,並且正在被應用到其他控制器。我只將該屬性應用於一個特定的控制器。這看起來像一個錯誤。 –

回答

12

基於以上的評論,以下是每個控制器配置的一個例子:

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

你認爲你可以指出我在正確的方向使這個論證按照控制器方法工作嗎? – WillFM

相關問題