.NET (core) has OpenAPI support through Swashbuckle, a NuGet package that generates OpenAPI metadata based on your API controllers.
I was asked to manipulate the Swagger metadata to exclude a specific property from the document metadata.
I found 2 possible solutions to achieve this goal:
Option 1 – Add a JsonIgnore attribute on your object:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Product | |
{ | |
[JsonIgnore] | |
public int Id {get;set;} | |
public string Name {get;set;} | |
} |
Option 2 – Create a SchemaFilter:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SwaggerIdFilter : ISchemaFilter | |
{ | |
public void Apply(Schema model, SchemaFilterContext context) | |
{ | |
model.Properties.Remove("id"); | |
} | |
} |
Don’t forget to register the filter in your Swagger configuration:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
httpConfiguration | |
.EnableSwagger(c => | |
{ | |
c.SchemaFilter<SwaggerIdFilter>(); | |
}); |