Model Validations with Minimal APIs in .NET
Eduardo Fonseca
Founder | Entrepreneur | Blazor Developer | Software Architect | .NET & Azure Expert | Cloud Architect | Creator of FairPlayTube | Software Engineer | Author | Digital Content Creator | Game Developer | Tech Innovator
Hello, I hope you are doing great.
Today I want to talk about Model Validation using Minimal APIs. As far as I know, Minimal APIs do not have model validation by default, which makes sense, since minimal APIs are especially designed to be fast, and that means removing a lot of additional functionality from the out of the box option, still, I haven't found any extension method like UseModelValidations, closest I have seen is ProducesValidationProblem, and while useful, it is not the same I was looking for, and seems to be used along with the "MiniValidation" library owned by Damian Edwards: https://github.com/DamianEdwards/MiniValidation
There are also wide used libraries such as FluentValidation, however, here we will discuss about how to do it yourself.
First of all, .NET offers as class named Validator, part of the ComponentModel set of namespaces
This class offers out of the box functionality to validate objects, basically it has a set of validation methods, some of these methods return the list of errors, while others throw an exception.
In this specific case what we chose to do is use the version which throw an exception
领英推荐
You basically pass the instance of the object you want to validate, as well as a ValidationContext which also received an instance of an object, additionally, we set the validateAllProperties to true.
This solution, while useful, it still something I am not really fond of, because it requires to manually code the validation logic inside the method's body, for every single Minimal API endpoint you need to add, contrary to the well know and trusted Controllers and MVC where you can set the model binder to automatically perform the validations, effectively removing the need of manually write validation logic for each single endpoint requiring validation, there might still be an approach to do something similar, which I plan to try soon, and that is create an extension method which inspects the request and perform the validation effectively doing something like
app.MapPost(...).RequiresModelValidation()
I hope this article has been useful.
Remember you can help me help you learn by becoming a sponsor: https://github.com/sponsors/efonsecab
Subscribe to my YouTube channel here: https://www.youtube.com/c/pticostaricags