user2585188
user2585188

Reputation: 45

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.

Upvotes: 2

Views: 2955

Answers (2)

Al Sh
Al Sh

Reputation: 31

You can do it like this:

  1. Create custom validation attribute, for example UniqueAttribute

    public class UniqueAttribute : ValidationAttribute { ... }
    
  2. Apply this attribute to a model property

    [Unique]
    public string Name { get; set; }
    
  3. Implement ISchemaFilter interface extension

    public class AddUniquenessDescriptionFilter : ISchemaFilter
    {
      public void Apply(OpenApiSchema schema, SchemaFilterContext context)
      {
        var attr = context.MemberInfo?.CustomAttributes.Where(x => 
             x.AttributeType.Name == nameof(UniqueAttribute)) 
             .FirstOrDefault();
    
        if (attr is not null)
        {
          schema.Extensions.Add("isUnique", new OpenApiBoolean(true));
        }
      }
    }
    
  4. And use extension on startup

    builder.Services.AddSwaggerGen(options => 
    { 
      options.SchemaFilter<AddUniquenessDescriptionFilter>(); 
    });
    

The results look like this: Swagger documentation

Here is a full example: Custom ValidationAttribute

Upvotes: 3

user2585188
user2585188

Reputation: 45

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)

Upvotes: 0

Related Questions