Search code examples
c#swaggerswagger-uivalidationattribute

Add Custom ValidationAttribute to Swagger Documentation


I have a custom validation attribute

Lets say I have a HelloWorld class that implements ValidationAttribute. I then apply this attribute to a field within my API.

[HelloWorld]
public string FirstName { get; set; }

When I generate the Swagger UI, I get a JSON OpenAPI spec and the model displays the properties of each field like below:

enter image description here

If I add a Required tag, a asterisk is displayed If I use attributes like RegularExpression/Range/StringLength, text appears to specify this. However, I would like to make someone aware of the custom validation, with my own description.

Is it possible?

Any help would be much appreciated. I've spent all day looking at DocumentFilter/SchemaFilter/OperationFilter, but can't find any good documentation or examples.


Solution

  • I was trying to use OperationFilter, but it wasn't supported on .Net Framework 4.1.

    I would have to use the filters to amend the documentation (I believe this is the was x-extensions is utilised)