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 –

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
        {
            options.Filters.Add(typeof(ValidateModelAttribute));
        })
        .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<PersonModelValidator>());
}

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

Step 3

Add the validation filter –

public class ValidateModelAttribute : ActionFilterAttribute
{	
    public override void OnActionExecuting(ActionExecutingContext context)	
    {	
        if (!context.ModelState.IsValid)	
        {	
            context.Result = new BadRequestObjectResult(context.ModelState);
        }
    }
}
Step 4

Add a model and a validator.

public class PersonModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class PersonModelValidator : AbstractValidator<PersonModel>
{
    public PersonModelValidator()
    {
        RuleFor(p => p.FirstName).NotEmpty();
        RuleFor(p => p.LastName).Length(5);
    }
}

Full source code available here.

6 thoughts on “Fluent Validation in ASP.NET Core

  1. Running your code, the validators never fire and the POST results in a null ref in the controller. Has something changed since this was written?

    • Are you running my solution?
      Or did you copy/paste the code into your solution?

      If the latter, see steps 2 & 3 in blog post.

      Let me know.

      Bryan

  2. ‘IMvcBuilder’ does not contain a definition for ‘AddFluentValidation’ and no extension method ‘AddFluentValidation’ accepting a first argument of type ‘IMvcBuilder’ could be found (are you missing a using directive or an assembly reference?)

    I am getting this error even though I am adding all the namespaces.Please resolve this issue

  3. using FluentValidation;
    using System;

    namespace ErrorPoc.Models
    {
    public class LoginModel
    {
    public string UserName { get; set; }
    public string Password { get; set; }
    }
    public class LoginViewModelValidator : AbstractValidator
    {
    public LoginViewModelValidator()
    {
    RuleFor(reg => reg.UserName).NotEmpty().WithMessage(“Username should not be empty”);
    RuleFor(reg => reg.Password).NotEmpty().WithMessage(“Password should not be empty”);

    }

    }
    }

    This is my model class.I dont know where I am going wrong..I am not getting any validation message while performimg post operation.Please help

Leave a Reply

Your email address will not be published. Required fields are marked *