Performance is king (well, after accuracy) in APIs. Sending a request to the Database only to discover that the request is invalid is a waste of resources. Thus, we want to validate the request as soon as it hits the endpoint.
FluentValidation is a great tool for creating validators. It installs as a NuGet package. Also grab the version for ASP.Net.
To get going, add a using statement.
Using FluentValidatio
n
Next, create a class that derives from AbstractValidator.
public class CarNotDeletedValidator : AbstractValidator<Car>
This example uses the Car class from my forthcoming book Creating .NET APIs with C#.
Put your validation rules in the constructor. Each rule is created by using the keyword RuleFor and a lambda expression that indicates which property you want to validate and the validation rule.
using Cars.Data.DTOs;
using FluentValidation;
namespace Cars.Validators
{
public class CarNotDeletedValidator : AbstractValidator<CarDto>
{
public CarNotDeletedValidator()
{
RuleFor(x => x.Is_Deleted).Equal("0");
}
}
}
The Equal operator is one of many that you can find at the FluentValidation documentation page: https://docs.fluentvalidation.net/en/latest/built-in-validators.html.
We’ll test the data and then either compare it to what is valid and return an error if appropriate, or, more commonly, we’ll throw an exception if the data fails validation.
Assuming that it passes validation we can continue to the Database. If however it fails, we can return a meaningful error to the sender.
Admiring the commitment you put into your blog and detailed information you present. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed material. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.
Today, with all the fast life-style that everyone leads, credit cards have a huge demand throughout the market. Persons from every arena are using credit card and people who aren’t using the card have lined up to apply for one. Thanks for giving your ideas in credit cards.