【问题标题】:Swashbuckle generated API document with not well-format JSON in example propertiesSwashbuckle 生成的 API 文档在示例属性中的 JSON 格式不正确
【发布时间】:2021-11-25 07:04:51
【问题描述】:

将 Swashbuckle.AspnetCore 从版本 5.3.0 升级到 6.1.4 后,我遇到了与swagger.json 文件相关的问题,如下图所示。每个 example 属性中都有特殊字符 (BOM - 0xFEFF)。它使 JSON 文件格式不正确。

我尝试在其他项目中重现,但没有发生。

配置 Swagger 生成

     private static void RegisterSwagger(IServiceCollection services, IEnumerable<OpenApiServer> openApiServers)
        {
            services.AddSwaggerGen(options =>
            {
                foreach (var api in ApiInfo.ApiVersions)
                {
                    options.SwaggerDoc(api.Version, new OpenApiInfo
                    {
                        Title = api.Title,
                        Version = api.Version,
                        Description = api.Description,
                        Contact = api.Contact
                    });
                }

                options.ExampleFilters();
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
                options.DocumentFilter<DocumentFilter>();
                options.CustomSchemaIds(x => x.FullName);

                // OAS Rule: oas3-api-servers
                foreach (OpenApiServer server in openApiServers)
                {
                    options.AddServer(server);
                }

                // OAS Rule: operation-operationId
                // Use method name and HTTP method as operationId
                options.CustomOperationIds(apiDesc =>
                {
                    return apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? $"{methodInfo.Name}_{apiDesc.HttpMethod}" : null;
                });

                // OAS Rule: query-strings-camel-case
                options.DescribeAllParametersInCamelCase();
            });
            
            services.AddSwaggerExamplesFromAssemblyOf<DataRequestSwaggerExample>();
        }

【问题讨论】:

    标签: asp.net-core asp.net-web-api swashbuckle swashbuckle.aspnetcore


    【解决方案1】:

    我找到了根本原因。 我使用来自Swashbuckle.AspNetCore.FiltersExampleFilter。此过滤器使用MvcOutputFormatter 进行序列化。目前,我将MvcOutputFormatter 自定义为JSON 格式。 更新 Json 序列化程序后,输出格式正确

    https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters/blob/master/src/Swashbuckle.AspNetCore.Filters/Examples/ExamplesConverter.cs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-30
      • 2021-04-13
      • 2020-06-20
      • 2017-01-05
      • 2022-01-18
      • 2020-06-10
      • 1970-01-01
      • 2014-02-15
      相关资源
      最近更新 更多