Swagger文档中的camelCase

3

在Swagger文档中,是否可以将属性名称更改为驼峰命名法?我正在使用.NET Core 2.2和Swashbuckle.AspNetCore 5.2.1。我尝试在Startup.cs中使用DescribeAllParametersInCamelCase()方法,但没有任何变化。帮帮我!

我的模型:

    {
        public int MyProperty1 { get; set; }
        public int MyProperty2 { get; set; }
        public int MyProperty3 { get; set; }
    }

并且 swagger.json 是为其在 POST 方法中生成的:

 "components": {
    "schemas": {
      "TestModel": {
        "type": "object",
        "properties": {
          "MyProperty1": {
            "type": "integer",
            "format": "int32"
          },
          "MyProperty2": {
            "type": "integer",
            "format": "int32"
          },
          "MyProperty3": {
            "type": "integer",
            "format": "int32"
          }
        }
      }
    }
  }

如何更改为:

 "components": {
    "schemas": {
      "testModel": {
        "type": "object",
        "properties": {
          "myProperty1": {
            "type": "integer",
            "format": "int32"
          },
          "myProperty2": {
            "type": "integer",
            "format": "int32"
          },
          "myProperty3": {
            "type": "integer",
            "format": "int32"
          }
        }
      }
    }
  }

?

1个回答

4

我遇到了同样的问题,这是我的解决方法:

我实现了一个自定义过滤器(ISchemaFilter),该过滤器执行以下操作:

    public class CamelCasingPropertiesFilter : ISchemaFilter {
        public void Apply(OpenApiSchema model, SchemaFilterContext context)
        {
            model.Properties =
                model.Properties.ToDictionary(d => d.Key.Substring(0, 1).ToLower() + d.Key.Substring(1), d => d.Value);
        }
    }

也许我不知道还有更可靠的解决方案。这个问题很重要,因为openapi定义作为生成API客户端的基础。openapi生成器将构建具有PascalCase属性名称的类,当使用时API将抛出异常...

希望能帮到您!


2
对于像我这样不知道在哪里应用过滤器的人,这里有一个提示:在 Startup.csConfigureServices(...) 方法中添加以下代码:services.AddSwaggerGen(c =>{c.SchemaFilter<CamelCasingPropertiesFilter>(); ... }); - turanszkik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接