如何配置Swagger/Swashbuckle自定义序列化程序IControllerConfiguration ASP.NET WebAPI

Kri*_*ris 10 c# asp.net asp.net-web-api swagger swashbuckle

我有一个WebAPI端点,它实现了两个不同版本的API(旧版和新版).旧端点使用特定的串行器,该序列化器将所有对象序列化为带有下划线的小写字,v2端点使用驼峰式属性名称.例如,V1 ="document_type",V2 ="documentType"

目前使用控制器特定属性来定义序列化,如下所示:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

当通过REST从客户端调用时,这一切都正常,但Swagger生成的文档始终使用旧的序列化器设置显示属性名称.有关配置swashbuckle以正确序列化每个版本的任何建议吗?

Moh*_*mad 1

据我所知,swagger 使用Formatters可以找到的第一个设置。所以如果你使用这个:

controllerSettings.Formatters.Insert(0, new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } });
Run Code Online (Sandbox Code Playgroud)

Swagger 生成的文档就可以了。swagger 是一个非常好的库,我希望他们能够尽快解决这个问题。