2015-04-17 32 views
12

我在ASP.NET webapi項目中使用了Swashbuckle 5以及所有默認設置。它序列化我的方法的輸出,以顯示答案的模式。我得到的文件,看起來像這樣:k__BackingField在C#中刪除(通過Swashbuckle/Swagger看到)

Response Class (Status 200) 
Model Model Schema 
[ 
    { 
    "<Key>k__BackingField": "string", 
    "<Value>k__BackingField": "string", 
    "<Id>k__BackingField": 0 
    } 
] 

這是由下面的C#代碼生成

/// <summary> 
    ///  Fetches all system configuration items 
    /// </summary> 
    /// <returns>List of <see cref="SystemConfigurationDto" /> items</returns> 
    public IList<SystemConfigurationDto> GetAllSystemConfigurationItems() 
    { 
     var result = CommandProcessor.ProcessCommand(new SystemConfigurationQueryCommand()) as SystemConfigurationQueryCommandResponse; 

     return result.Results.ToList(); 
    } 

其中result.Results基本上是對象的標準列表,每個都包含這些鍵/值/ ID領域。我已經在這裏讀了https://conficient.wordpress.com/2014/05/22/getting-rid-of-k__backingfield-in-serialization/ [serializable]屬性可能會影響這個,但如果可能的話,我不願意去掉那個屬性。是否有任何配方來調整這個序列化神器?

回答

20

一下添加到WebApiConfig.cs

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = 
    new DefaultContractResolver { IgnoreSerializableAttribute = true }; 

這解決了標有[Serializable]類的問題。即使沒有類具有該屬性,我也有間歇性問題,所以我現在總是使用此設置。

+0

這讓我一整個早上。今天早上我突然遇到它升級了一些NuGet軟件包。該解決方案之前幾個月工作得很好。 '[Serializable]'屬性不是,並且從未在任何地方使用過。添加此代碼段解決了它。非常感謝你,先生! – ceej

+0

謝謝,也爲我工作 – spooti