Fluent Validation on .Net Core API (3.1)

Beril Kavaklı
4 min readMay 11, 2020

--

In this article, I will try to tell how we can validate a model on .Net Core API by using Fluent Validation. In addition, I will also use Action Filter on validation process.

If I summarily mention about the project concept, It is about posting product to RESTful API. I have been working on software products in retail scope and In retail systems, product information is generally integrated from another system like ERP. So we need to open an endpoint to get product information.

Before start, If you use Visual Studio, be sure you have 2019 version. Because .Net Core 3.1 is not supported on VS 2017 or older versions.

Let’s start step by step!

  1. Create .Net Core API Project

I have created a new project named SampleAPI.Core.3.1 by choosing ASP.NET Core web application and API.

2. Create Controller and Model for Product

When the project was created, there exists a sample implementation about weather forecast. I deleted them and created new controller and models that I needed. Also, I set the “launchBrowser” property false on launchSettings.json file. You can see the details below.

ProductController:

Models: Product and Price

3. Install FluentValidation from Nuget

I have chosen the FluentValidation.AspNetCore package to install. After that, We are ready to use Fluent Validation and write rules for our model.

4. Create Validators for Model

I have created validator classes that inherite from AbstractClass<T>. ‘T ‘ generic type must be our model that we want to validate. Our main model is Product and it contains a list of Price that is an object. I have created two validators. You can examine them below.

ProductValidator:

PriceValidator:

At this point, you can test Fluent Validation by using the code below in controller. But we haven’t done yet. I don’t want to write similar code blocks for all post methods in the project. Continue with next step…

5. Create Action Filter

Action Filters are invoked before and after controller and we will use ‘OnActionExecuting’ action for validation. You can see the class below.

6. Configure Startup.cs

This step we will configure Startup.cs for ActionFilter and FluentValidation.

7. Test

We are ready to test our validation. I will send two requests which first one is totally correct data and second one has some missing.

First request ends with 200 OK result.

Second request ends with 400 Bad Request result. You can see the validation errors in the screenshot.

I hope this article helps you while creating new API project and using Fluent Validation on .Net Core 3.1

You can reach the project solution on github with this link.

Happy coding day :)

--

--