ASP.NET Core 6.0 - implementing Data Annotations Validation in Custom Model Binder
I'm working with an scenario with data validation not working as expected in my ASP.NET Core 6.0 application when using a custom model binder. I've implemented a model binder that parses a complex object from the request body, but it seems that the data annotations on my model are being ignored. Here's the model Iβm using: ```csharp public class UserInput { [Required(ErrorMessage = "Username is required")] public string Username { get; set; } [EmailAddress(ErrorMessage = "Invalid email address")] public string Email { get; set; } [Range(1, 100, ErrorMessage = "Age must be between 1 and 100")] public int Age { get; set; } } ``` And my custom model binder looks like this: ```csharp public class UserInputModelBinder : IModelBinder { public async Task BindModelAsync(ModelBindingContext bindingContext) { var requestBody = await new StreamReader(bindingContext.HttpContext.Request.Body).ReadToEndAsync(); var userInput = JsonSerializer.Deserialize<UserInput>(requestBody); bindingContext.Result = userInput != null ? ModelBindingResult.Success(userInput) : ModelBindingResult.Failed(); } } ``` I've registered the custom binder in my `Startup.cs` like this: ```csharp services.AddControllers(options => { options.ModelBinderProviders.Insert(0, new UserInputModelBinderProvider()); }); ``` When I send a POST request with invalid data (e.g., missing the `Username`), I expect to see the validation errors based on the data annotations, but the model state is always valid. Iβve tried calling `Validator.TryValidateObject()` within my custom model binder, but it doesn't seem to be effective either. Hereβs how I'm attempting to validate: ```csharp var validationResults = new List<ValidationResult>(); var validationContext = new ValidationContext(userInput); if (!Validator.TryValidateObject(userInput, validationContext, validationResults, true)) { bindingContext.ModelState.AddModelError("", validationResults.First().ErrorMessage); } ``` Despite this, the `ModelState.IsValid` remains true. I also verified that the `ModelState` is not being cleared elsewhere. Any ideas on why the data annotations are being bypassed? Is there something I'm missing in how custom model binders interact with model validation in ASP.NET Core? Thanks in advance for your help!