Closed jameswilddev closed 6 years ago
All complex type parameters in an ApiController are bound from the request body. By design, the parameter inference does not look at attributes on properties on the parameter type. Adding [FromQuery]
on the parameter rather than the property should get you the behavior you're looking for here.
Many of our query parameters contain conditional validation which depends upon other query parameters, such as A must be set when B has value C, or only one of A or B can be set.
This can't be done with validation attributes on method parameters AFAIK (no validation context), only when encapsulated in an object as above.
Additionally, we can't write unit tests against validation attributes on method parameters, but writing tests against an encapsulating object is trivial (IObjectModelValidator).
Not supporting encapsulated requests is something of a deal-breaker for validation.
@jameswilddev there's a couple of alternatives to annotating the parameter with the attribute:
1) Turn off parameter inference using ApiBehaviorOptions.SuppressInferBindingSourcesForParameters
. You get the same behavior as a regular Controller
and have to annotate parameters with FromBody
if you're attempting to bind it from the request body.
2) Apply a [ModelBinder]
attribute to the parameter. This indicates that individual properties on the parameter can come from any source and the FromQuery
should work.
Thanks, I'll be sure to give those a try tomorrow when I'm back at the coal face ha!
That seems to work beautifully, thanks, you're a lifesaver
Is this a Bug or Feature request?:
Bug
Steps to reproduce (preferably a link to a GitHub repo with a repro project):
GET http://localhost:5000/test?param=a
Response:
Description of the problem:
Seems it should be valid to me. Removing [ApiController] gets me the expected 200 response with a body of "a".
Version of
Microsoft.AspNetCore.Mvc
orMicrosoft.AspNetCore.App
orMicrosoft.AspNetCore.All
: