domaindrivendev / Swashbuckle.AspNetCore

Swagger tools for documenting API's built on ASP.NET Core
MIT License
5.22k stars 1.3k forks source link

The [Required] attribute is not respected for non-nullable data type #736

Closed diouxis closed 6 years ago

diouxis commented 6 years ago

I am currently working with a Asp.NetCore WebAPI with Swashbuckle.

I noticed that when producing the swagger.json, the [Required] attribute cannot be recognised for any non-nullable type (e.g. int, DateTime).

I also create a pure Asp.NetCore WebAPI project for testing, and this issue is still coming.

Now, I have to use the following SchemaFilter to make it work:

if (propertyType.IsValueType
    && !(propertyType.IsConstructedGenericType && (propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))))
{
    if (property.CustomAttributes.Any(attr => attr.AttributeType == typeof(RequiredAttribute) ))
    {
        if (model.Required == null)
        {
            model.Required = new List<string>();
        }
        model.Required.Add(schemaPropertyName);
    }
}

Is this a bug or I missing some configurations?

diouxis commented 6 years ago

All good, I found out this is the problem about user-posting, so it is not the issue for swagger since even it is labelled as [Required] the ModelState still cannot catch the missing for a non-nullabe property.