如何配置 Swagger/Swashbuckle 自定义序列化程序 IControllerConfiguration A

本文关键字:自定义 Swashbuckle 序列化 程序 IControllerConfiguration Swagger 何配置 配置 | 更新日期: 2023-09-27 18:35:05

我有一个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());
    }
}

当通过 REST 从客户端调用时,这一切都可以正常工作,但 Swagger 生成的文档始终使用旧序列化程序设置显示属性名称。 关于配置虚张声势以正确序列化每个版本的任何建议?

如何配置 Swagger/Swashbuckle 自定义序列化程序 IControllerConfiguration A

我所知,Swagger首先使用可以找到的Formatters设置。 因此,如果您使用它:

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

您的文档由 Swagger 生成会很好。Swagger是一个非常好的库,我希望他们能尽快解决这个问题。