Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Swagger/Swashbuckle custom serializer IControllerConfiguration ASP.NET WebAPI

I have a WebAPI endpoint that implements two different versions of the API (legacy and new). The legacy endpoints use a specific Serializer that has all objects serialized as lower case words with underscores, the v2 endpoint uses camel cased property names. For example, V1 = "document_type" and V2 = "documentType"

This is currently achieved using controller specific attributes to define the serialization, like so:

public class CamelCaseControllerConfiguration : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        controllerSettings.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        controllerSettings.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
    }
}

This all works fine when called from a client via REST, but the documentation generated by Swagger always shows the property names using the legacy serializer settings. Any suggestions on configuring swashbuckle to serialize each version properly?

like image 570
Kris Avatar asked Feb 16 '16 19:02

Kris


1 Answers

as far as i know swagger use first Formatters settings that can find. so if you use this:

controllerSettings.Formatters.Insert(0, new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } });

your documentation generated by Swagger will be fine. swagger is a very good library and i hope they can fix this problem soon.

like image 76
Mohammad Avatar answered Sep 28 '22 04:09

Mohammad