How do you deal with required value types in input models without having to make all of them nullable?
For a long time, the only solutions out there suggested:
- Using
[BindRequired]
, which doesn't work for body data. - Using something like
[Range]
, which only works for integers and only if they cannot be zero. - Just making all your properties nullable, which is ugly.
But you can actually get your input models looking like this by making a custom value provider & model binder:
record InputModel
{
[Required(ErrorMessage = "Optional custom error")]
public int NonNullableInteger { get; init; }
}
The entire tutorial is kept updated on my blog, alongside source code and an example project: https://thom.ee/blog/clean-way-to-use-required-value-types-in-asp-net-core/
Top comments (0)