I’m using some versioning techniques in web api that will basically call a controller based on a specified api version in the header. So the scenario, lets say we have an entry point called api/GetSalesHistory but our server guys (me) had to change the request contract in order for us to do what we need to do. In some cases, this becomes a breaking change (such as a new required field, or a single value that has been changed to a list), hence the versioning.
So, my routing selector will look in the header for an api version and then call the correct controller. The version 1 controller has a parameter type of the version 1 request, and the version 2 controller has a parameter type of the version 2 request.
Here’s the problem. Out of the box, the controller will run regardless of the payload you send it. Back in WCF, if you sent in the wrong object, serialization would fail causing the entire request to fail. Right now, what happens is if I send the version 1 payload to the version 2 controller, instead of failing serialization or failing the request, it’ll create an instance of the version 2 request with empty fields and then continue to run. So the parameter doesn’t come in as null, so I can’t simply say if(request == null) explode;
How do I force the controller to reject the request if the expected payload is not received?
I had forgotten that you can use ModelState.IsValid and it will address the target in context. I simply check: