As far as I understand it, value types implicitly have the [Required]
attribute when MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes
is set to false
. But I frankly can't see any difference when I switch it between the two.
Furthermore, if i explicitly use the [Required]
attribute on a non-nullable type, such as an int
, it will require of me to set its value, rather than just hitting the endpoint without the given int
parameter, which would be assigned a default value for its type - 0
.
So, to summarize:
If it implicitly adds the [Required]
attribute, why does the explicit variant offer completely different functionality?
Is there any functional difference for enabling/disabling MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes
? From what I can see, it doesn't change anything.
I actually haven't tried this setting yet, but I think the clue is in the name: SuppressImplicitRequiredAttributeForNonNullableReferenceTypes.
Sounds like it doesn't apply to value types. It applies to non-nullable reference types.
As you said, a property with type int
will always have a default value, the model validator doesn't know if the value was missing or if it was set to that.
However, if you enable C# 8 nullable reference types, you could have properties like:
public string A { get; set; }
public string? B { get; set; }
Now with that setting set the A
property gets the Required attribute.
It is still a reference type and can be null.
Thus the check makes sense.