Swashbuckle - 将 DisplayName 添加到模型属性

Swashbuckle - add DisplayName to model properties

我在 .NET Core 应用程序中使用 Swagger/Swashbuckle。 如何在 swagger.json 输出文件中添加模型属性的显示名称?

这是我的模型:

 public class Role
    {
        [DisplayName("Role Name")]
        public string Name { get; set; }
        public int Level { get; set; }
    }

这里是当前输出

"Role": {
   "properties": {
      "Name": {
         "type": "string"
      },
      "Level": {
         "format": "int32",
         "type": "integer"
      }
   }
}

此处是所需的输出:

"Role": {
   "properties": {
      "Name": {
         "displayName": "Role Name",
         "type": "string"
      },
      "Level": {
         "displayName": "Level",
         "format": "int32",
         "type": "integer"
      }
   }
}

正如我在评论中提到的,"displayName" 不在规范中

我刚刚将其添加到我的一个文件中以查看验证期间会发生什么:
https://validator.swagger.io/validator/debug?url=https://raw.githubusercontent.com/heldersepu/hs-scripts/master/swagger/56287697_swagger_aws.json

我们可以看到验证器不喜欢那样,我们得到一个错误:

{
  "schemaValidationMessages": [ {
    "level": "error",
    "domain": "validation",
    "keyword": "additionalProperties",
    "message": "object instance has properties which are not allowed by the schema: [\"displayName\"]",
    "schema": {
      "loadingURI": "http://swagger.io/v2/schema.json#", "pointer": "/definitions/schema"
    }
    ,
    "instance": {
      "pointer": "/definitions/MyData/properties/name"
    }
  }
  ]
}

您可以提议对规范进行更改,但不要指望它会很快添加:
https://github.com/OAI/OpenAPI-Specification/issues


我看到的唯一快速选项或解决方法是使用扩展:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
您可以使用 IDocumentFilter 注入那些:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/search?q=IDocumentFilter

看起来 IDocumentFilter 在最新版本上有一些重大变化:

你想要的输出会稍微改变一下:

"Role": {
   "properties": {
      "Name": {
         "x-displayName": "Role Name",
         "type": "string"
      },
      "Level": {
         "x-displayName": "Level",
         "format": "int32",
         "type": "integer"
      }
   }
}

您可以使用开箱即用的 JsonPropertyName() attribute 而不是 DisplayName() attribute

public class Role
    {
        [JsonPropertyName("Role Name")]
        public string Name { get; set; }
        public int Level { get; set; }
    }