k__BackingField remove in C# (seen via Swashbuckle / Swagger)

妖精的绣舞 提交于 2019-12-18 19:41:29

问题


I am using Swashbuckle 5 in my ASP.NET webapi project with all default settings. It serializes my method's output in order to show me schema of the reply. I am getting documentation that looks like this:

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

This is generated by following C# code

    /// <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();
    }

where result.Results is basically a standard List of objects, each containing these key/value/id fields. I have read here https://conficient.wordpress.com/2014/05/22/getting-rid-of-k__backingfield-in-serialization/ that [serializable] attribute might affect this but I am not willing to get rid of that attribute, if possible. Is there any recipe to adjust this serialization artifact?


回答1:


Add this to WebApiConfig.cs:

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

This resolves the issue for classes marked with [Serializable]. I also have intermittent problems even if no classes have that attribute, so I always use this setting now.



来源:https://stackoverflow.com/questions/29701891/k-backingfield-remove-in-c-sharp-seen-via-swashbuckle-swagger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!