DEV Community

Thomas
Thomas

Posted on • Edited on

A clean way to use required value types in ASP.NET Core

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; }
}
Enter fullscreen mode Exit fullscreen mode

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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay