🔧 This article assumes you areusing a modern version of .NET and C#, I am using .NET 8.
🧑💻 This article assumes you have intermediate experience with the command line.
Setting up a new Web Api
First launch a new console, I am using Windows Terminal with bash inside WSL. But anything works, really.
This will launch Visual Studio code on the new created project.
As you might see in our command line code, we are gonna use SQLite for this example program.
Open the integrated terminal, and start installing packages:
This adds FluentValidation itself and a newly created package from SharpGrid that makes ASP.Net use the validators automatically, check out their Github for more information.
Let’s continue setting up Entity Framework Core with SQLite.
Open the newly created file TodoItem.cs
in VSCode and write the following code:
Setting up the database context
Let’s create a DataContext.cs
file in the Models
folder.
Write the following code:
Now we need to make use of dependecy injection to register the DataContext
class.
Update Program.cs
with the following code:
💡 Now the
DataContext
is available for depenceny-injection, making it very easy for controllers and services to access it. Addionally, we added a Connection String for the database.
Creating a controller
Create the controller file.
Copy & paste the initial code:
This is our initial code, now lets make sure to add the DataContext
to the primary constructor (which is a new feature in C# 12, btw.)
Let’s add some endpoints, this code goes inside the class.
💡 The first endpoint is for querying an Item using an Id, and the second item is for creating a new item.
Before we can test this endpoints, we need to update our database and create the first migration:
💡 This created our initial database schema and migration, now our app is ready to use the database.
Open two consoles, on the first one run the api:
Take notice of the port it is running, in my case it is 5019, but it varies on project creation.
Notice: When the testing ends, press
Control+C
(or⌘+C
on Apple computers) to stop the Api.
On the other one, we are gonna use curl
to send a request:
If everything is successful, we should get a response that looks similar to this:
Take note of the id
, so we can test the GET endpoint, just to make sure:
Should print the same response.
Adding Validations
First we will create a validator for our TodoItem entity:
Copy-paste the following code:
💡 What this class does is validate the Entity
TodoItem
and checks that the fieldName
has a minimum length of 10 characters.
Now that we have a validator, we need to register it to the dependency-injection system that ASP.NET uses,
the package we installed before SharpGrip.FluentValidation.AutoValidation.Mvc
requires all validations to be registered.
For now we only have one, but this can quickly scale to 10 or more than 100 depending on how big our program is.
Luckily, I came up with a solution using reflection, for this we are gona create an extension class.
Copy paste the following code:
What this code does exactly:
-
It finds all the Types that are contained within a provided namespace, that are not abstract or interfaces and their names end with “Validator”.
-
Then it filters them to those that implement the interface
IValidator
-
It registers those types in the dependency injection for our app.
-
It makes use of the package provided extension
SharpGrip
to make all the validations work.
To use this extension lets change our Program.cs
Notice this changes:
- Add the using to our custom extension.
- Call the
AddFluentValidation
method we just created passing thenamespace
that contains all the validators.
Let’s try it out, as usual start the api:
And let’s use curl to create another TodoItem, this time it will have a short item name:
You should get this error:
Now let’s fix this error by creating a new item that satisfies our validation:
Here is the response:
🎊 Congratulations, you just setup FluentValidation correctly.
You can create more validators as long as their namespace starts with TodoApi.Models.Validators
.
Happy coding!