billbogaiv / hybrid-model-binding

Provides the ability to bind models using both ModelBinder and ValueProvider in ASP.NET Core.
MIT License
104 stars 19 forks source link

Model is not validated #41

Closed agolaszewski closed 3 years ago

agolaszewski commented 4 years ago

My controller has the annotation [ApiController] which by default triggers automatic model validation and sends 400 response. However this functionality stops working when using hybrid-model-binding. I created ActionFilter to do that manualy but context.ModelState.IsValid always return true even if I send empty body. I am using .net core 2.2. Any idea why?

billbogaiv commented 4 years ago

For GET requests, #hybridmodelbinding has to construct the model itself. It will first attempt to get an instance via .NET Core's dependency-injection. If that fails, it attempts to brute-force via Activator.CreateInstance. The current implementation is rudimentary so if your model has constructor-parameters, the latter won't work and marks the binding-result as ModelBindingResult.Failed(). Because the model is null at this point, validation doesn't get applied and the ModelState in any ActionFilter would be listed as valid. For now, if this matches your scenario, I'd recommend registering the model into the Startup's service collection.

For POST/PUT requests, things get a bit easier since the ASP.NET BodyModelBinder does the initial model creation. Therefore, having issues with model validation shouldn't be a problem.

I've thought about the whole constructor-parameter scenario and don't plan on adding code into the library to parse parameter-types and all that, but may opt for something like JSON.NET. When this change happens, I'll try and remember to reference this issue.

billbogaiv commented 4 years ago

Linking to this comment for reference regarding model initialization: https://github.com/billbogaiv/hybrid-model-binding/issues/34#issuecomment-495040849