Stam
Stam

Reputation: 2490

How to display a custom validation attribute in swagger ui inside the web dto schema

In a .NET Core 3.1 api project I have integrated swagger ui.

In a web dto schema in the swagger ui, I am able to see that a basic data annotation attribute (like Required, StringLength etc. ) has been applied to a property for validation.

I would like to display as well a custom attribute if this has been applied to a property of a web dto.

For example:

public class AttachmentGetInfoWebDto
{

    [IsNewerThan(minYear: 1928, "You cannot select an attachment older than 1928")]
    public int FromYear { get; set; }
}

It would be great if I could display to the shema of the AttachmentGetInfoWebDto that you are not allow ed to pass a value for the property FromYear less that 1928. Is this possible?

Upvotes: 6

Views: 1372

Answers (1)

Paramjeet Singh
Paramjeet Singh

Reputation: 46

You can do it like this:

Create custom validation attribute, for example UniqueAttribute

public class UniqueAttribute : ValidationAttribute { ... }

Apply this attribute to a model property

[Unique]
public string Name { get; set; }

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));
}
}
}

And use extension on startup

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

Upvotes: 3

Related Questions