14

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?

onkami
  • 8,791
  • 17
  • 90
  • 176

1 Answers1

30

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.

Alex Angas
  • 59,219
  • 41
  • 137
  • 210
  • This has had me all morning. I suddenly encountered it this morning having upgraded some NuGet packages. The solution has previously worked just fine for several months. The `[Serializable]` attribute is not, and has never been, used anywhere. Adding this code snippet solved it. Much obliged to you sir! – ceej Jul 15 '15 at 12:46
  • For me this solved the "k__BackingField problem" but after this changed the clients of older API method ceased to receive data – Marco Forberg Sep 12 '18 at 06:39