ASP.NET Core Custom Request Validation Middleware
In modern ASP.NET Core development, validation is a critical, non-negotiable part of building robust APIs. The default approach often involves using data annotations and checking ModelState within controller actions or using filters. While this works, it can lead to scattered validation logic and boilerplate code, especially in larger applications.
A more powerful and centralized approach is to use custom middleware for request validation. This strategy intercepts requests early in the pipeline, validates them, and rejects them before they even reach your API endpoints. This not only cleans up your endpoint logic but also creates a single, consistent validation gate for your entire application.
In this post, we’ll build a custom validation middleware from scratch, integrating the popular FluentValidation library to create a clean, efficient, and scalable validation system that completely bypasses ModelState.
The Problem with Traditional Validation
The standard [ApiController] attribute in ASP.NET Core automatically triggers model validation and returns a 400 Bad Request if ModelState is invalid. This is convenient but has a few drawbacks:
- Coupling: The validation logic is tightly coupled to the MVC/API Controller framework. It’s less straightforward to apply the same automatic behavior consistently in Minimal APIs without extra boilerplate.
- Scattered Logic: Validation rules defined via attributes can become unwieldy and are spread across numerous DTOs.
- Repetitive …