Data annotation .NET 8 additions in an Web API example

There are some awesome data annotations added to .NET 8 to help improve model validation in an ASP.NET Core Web API.

These include:

  • AllowedValues - Specifying which values are allowed for a property to validate
  • DeniedValues - Denying certain values from a property
  • Length - Specifying the minimum and maximum number of items in a List type
  • Base64String - Validating a string to ensure that it's Base64 encoded

In-addition, the Range attribute now includes the MinimumIsExclusive and MaximumIsExclusive. This means that if they are set to true and the value equals the minimum or maximum, it will not validate.

Software

This is the software that will need to be installed onto your machine.

Get the application working

These are the steps to get the application working.

  • Fill out the code example form. We will send you an email where you can download the code example.

You are now ready to go.

Open the project in Visual Studio

Open up RoundTheCode.DotNet8DataAnnotations.sln in Visual Studio 2022.

C# coding challenges

C# coding challenges

Our online code editor allows you to compile the answer.

Start the project in Visual Studio. It will load up https://localhost:10002/swagger/index.html.

Test the /api/MyValidation endpoint for validation. It will use the validation that is added in the MyValidationModel class.

If the endpoint does not validate, it will return a 400 Bad Request response and will list all the model validation errors. If it does validate, it will return a 200 OK response.

More information

Watch our video where we go ahead and test out some of the data annotations that have been added to .NET 8.

As well as that, read our tutorial where we explain how each data annotation works in ASP.NET Core Web API model validation.