Skip to content

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

License

Notifications You must be signed in to change notification settings

fuine6/required-value-types

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Required Value Types

How do you deal with required value types in input models without having to make all of them nullable?

Implementation & sample controller are provided.

Read the article/tutorial here.

How to use

Copy over the RequiredValueTypes folder to your project.

Then add the following line, somewhere after any other services that change MvcOptions:

builder.Services.UseExplicitRequiredValueTypes();

Now you can use the [Required] attribute in your input models and it'll work with value types.

Sample

public record PersonInputModel
{
    [Required(ErrorMessage = "Provide an ID.")] public int Id { get; init; }
    public int? Age { get; init; }
    public string Name { get; init; } = null!;
}

public record PersonAtLocationInputModel
{
    [Required] public decimal Latitude { get; init; }
    [Required] public decimal Longitude { get; init; }
    [Required] public PersonInputModel Person { get; init; } = null!;
}

public class AppController : ControllerBase
{
    [Route("app")]
    public IActionResult App([FromBody] PersonAtLocationInputModel inputModel)
    {
        if (!ModelState.IsValid) {
            return BadRequest(ModelState);
        }

        return Ok(inputModel);
    }
}

License

MIT. See LICENSE.md.

About

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 100.0%