Validation is a critical part of any application. There are various built-in ways to implement validation with ASP.NET Core, but there are alternatives.
FluentValidation is a .NET library for building strongly-typed validation rules. It uses a fluent interface and lambda expressions for building validation rules.
Step 1: For integration with ASP.NET Core, install the FluentValidation.AspNetCore package:
Step 2: Add FluentValidation in Startup.cs
To define a set of validation rules for a particular object, you will need to create a class that inherits from AbstractValidator, where T is the type of class that you wish to validate.
Step 1: Create a model you want to validate
Since I'm currently on an IoT project, I will use a Device model.
Step 2: Create your validator
Your validator must inherit from AbstractValidator. In this example, I'm doing some basic validation as well ensuring the DeviceId and MacAddress are in the correct formats.
Step 4: Declare your rules as a Singleton service in Startup.cs
Step 5: Manage your validation errors in Startup.cs
ASP.NET Core allows you to override the default behavior of ModelState management (ApiBehaviorOptions). You have now an alternative to MVC Attributes.
When validation fails, this piece of code is executed (ModelState is false).
I simply return an object that contains an error code, a message, and a list of validation errors.
You just need to create an action that takes in a parameter representing the model you want to validate.
Because the validation service was added in your configuration, FluentValidation will automatically detect your model when you submit a request to the controller's method.
Step 1: Create an action that uses your model to validate
Step 2: Test your action with PostMan
This was an example of implementing validation with FluentValidation and ASP.NET Core.