Reputation: 1473
I am using Swagger/Swashbuckle in a .NET Core app. How can I add the display name of my model attributes in swagger.json output file?
Here my model:
public class Role
{
[DisplayName("Role Name")]
public string Name { get; set; }
public int Level { get; set; }
}
Here the current output
"Role": {
"properties": {
"Name": {
"type": "string"
},
"Level": {
"format": "int32",
"type": "integer"
}
}
}
Here the desired output:
"Role": {
"properties": {
"Name": {
"displayName": "Role Name",
"type": "string"
},
"Level": {
"displayName": "Level",
"format": "int32",
"type": "integer"
}
}
}
Upvotes: 3
Views: 4247
Reputation: 31
Instead of using DisplayName() attribute
, you can use JsonPropertyName() attribute
which is out of the box.
public class Role
{
[JsonPropertyName("Role Name")]
public string Name { get; set; }
public int Level { get; set; }
}
Upvotes: 3
Reputation: 17604
Like I mentioned in my comments the "displayName" is not in the specifications
I just added that to one of my files to see what will happen during validation:
https://validator.swagger.io/validator/debug?url=https://raw.githubusercontent.com/heldersepu/hs-scripts/master/swagger/56287697_swagger_aws.json
We can see the validator does not like that, we get an error:
{
"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"
}
}
]
}
You could propose that change to the specification but don't expect it to get added any time soon:
https://github.com/OAI/OpenAPI-Specification/issues
The only quick option or workaround I see, will be using extensions:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
You can inject those using an IDocumentFilter:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/search?q=IDocumentFilter
Look like the IDocumentFilter has some breaking changes on the latest version:
Your desired output will change a bit:
"Role": {
"properties": {
"Name": {
"x-displayName": "Role Name",
"type": "string"
},
"Level": {
"x-displayName": "Level",
"format": "int32",
"type": "integer"
}
}
}
Upvotes: 2