I have a property that is annotated with a System.ComponentModel.DataAnnotations.MaxLengthAttribute
. I’d like this length restriction to be reflected in the Open API spec for the service. Is there a way to achieve this with the available filters? I think I’d need the original type and property name to get the attribute.
public class UpdateCustomer : IReturn<UpdateCustomerResponse>, IPost
{
[MaxLength(50)]
public string Name{ get; set; }
}
The basic idea how it can be done is to use OperationFilter
. As second parameter it consumes OpenApiOperation
which has RequestType
property. You can find your type by this RequestType
and find all properties which has [MaxLength]
attribute via reflection. Then iterate through Parameters
of operation and set MaxLength
property for all parameters which has this property.
new OpenApiFeature{
OperationFilter = (verb, op) => {
string requestTypeName = op.RequestType;
//get type by its string name (you can use any other approach, for example holding types in dictionary)
Assembly asm = typeof(Project.ServiceModel).Assembly;
Type type = asm.GetType(requestTypeName);
//find properties with [MaxLength] Attribute
var properties = ....
//set max length in Open API parameters
foreach(var prop in properties)
{
var attrValue = ... //get attribute value from property
op.Parameters.FirstOrDefault(p => p.Name == prop.Name)?.MaxLength = attrValue;
}
}
};
@xplicit thanks for this. I got it working on the path/operations. However I need to modify the parameters on the Schema Objects too. I’ll try and put a PR together to make the SchemaType
available on the OpenApiSchema
like RequestType
is on OpenApiOperation
.