Fluent Validation in ASP.NET Core 3.1
Full source code available here.
This is an update to a post I wrote in 2017 talking about Fluent Validation in ASP.NET Core.
The example is the same but there has been few updates. The first is how you setup the FluentValidation
in Startup.cs
, and the second is that you don’t need a ActionFilterAttribute
anymore. I have included an example of how to call the action method using Fiddler.
Step 1
Firstly add the package to your Web Api project.
Install-Package FluentValidation.AspNetCore
.
If you are going to keep your validators in the Web Api project that is all you need to add.
But if you put the validators in a different project you need to add the FluentValidation
package to that project
Install-Package FluentValidation
.
Step 2
In startup.cs
add -
1public void ConfigureServices(IServiceCollection services)
2{
3 services.AddControllers()
4 .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<PersonModelValidator>());}
Step 3
Add a model and a validator.
1public class PersonModel
2{
3 public string FirstName { get; set; }
4 public string LastName { get; set; }
5}
6
7public class PersonModelValidator : AbstractValidator<PersonModel>
8{
9 public PersonModelValidator()
10 {
11 RuleFor(p => p.FirstName).NotEmpty();
12 RuleFor(p => p.LastName).Length(5);
13 }
14}
Example Usage
In Fiddler, Postman or any other tool you POST to localhost:5000/person
with the following header -
Content-Type: application/json
And body -
1{
2 "firstName": "",
3 "lastName": "This is too long"
4}
Here is how the request looks in Fiddler -
The response will look like this -
1{
2 "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
3 "title": "One or more validation errors occurred.",
4 "status": 400,
5 "traceId": "|84df05e2-41e0d4841bb61293.",
6 "errors": {
7 "LastName": [
8 "'Last Name' must be 5 characters in length. You entered 16 characters."
9 ],
10 "FirstName": [
11 "'First Name' must not be empty."
12 ]
13 }
14}
Easy to read that there are two errors.
Full source code available here.