Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 518
onkami Avatar asked Apr 17 '15 14:04

onkami


1 Answers

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.

like image 130
Alex Angas Avatar answered Sep 21 '22 10:09

Alex Angas