This post is about implementing model validation in ASP.NET Core Minimal APIs. Minimal APIs do not come with any built-in support for validation. In this post we will explore how to build one and we explore will use some other libraries which can be used to implement validations.
You can implement a minimal validation library compatible with the existing validation attributes, like this.
And you can inject this as a service in your pipeline and use it like this.
In the MinimalValidator class, we are using Reflection and identifying ValidationAttribute classes and invoking the IsValid method, if it not valid, we are calling the FormatErrorMessage method and adding the error message to the Dictionary of result. It is very minimal implementation, and I didn’t tested it with all the validation attribute and custom validator implementations. And it will not work if the model object is a collection.
This package offers validation support for collection type models. As it is a static class no need to inject it in the pipeline. I think it becomes a challenge in the unit testing. Yes, you can wrap it into a service and do the testing.
Next one we can use FluentValidation it a popular validation library available in the market. But it can’t be used with existing validation attributes. You need to write validation code explicitly. To use this first you need to install the package - FluentValidation.AspNetCore. Next you can inject the validation service to the pipeline like this - builder.Services.AddFluentValidation(v => v.RegisterValidatorsFromAssemblyContaining<Program>());. And you need to create validator classes by inheriting AbstractValidator class. Here is an example.
And in the HTTP Post, you can use it like this.
I created an extension method which converts FluentValidation.Results.ValidationResult to Dictionary like this. Otherwise we can’t return the Results.ValidationProblem from the API endpoint.
It will give you the exact same results as we saw in the screenshot. And each method we used has its own pros and cons. Choose a validation library based on your requirements until ASP.NET Core team offers one out of the box for Minimal APIs.