Fluent Validation in ASP.NET Core

Full source code available here.

I have written about Fluent Validation a couple of times. There is a new library available for .Net Core.

How to return to validation messages back to the caller is not immediately obvious. You might see the validators running, but the responses are missing! Here is how to solve that problem.

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 projecty Install-Package FluentValidation.

Step 2

In startup.cs add -

1public void ConfigureServices(IServiceCollection services)
2{
3    services.AddMvc(options =>
4        {
5            options.Filters.Add(typeof(ValidateModelAttribute));
6        })
7        .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<PersonModelValidator>());
8}

Note the line options.Filters.Add(typeof(ValidateModelAttribute)), we need to add that filter.

Step 3

Add the validation filter -

 1public class ValidateModelAttribute : ActionFilterAttribute
 2{	
 3    public override void OnActionExecuting(ActionExecutingContext context)	
 4    {	
 5        if (!context.ModelState.IsValid)	
 6        {	
 7            context.Result = new BadRequestObjectResult(context.ModelState);
 8        }
 9    }
10}

Step 4

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}

Full source code available here.

comments powered by Disqus

Related