When creating a webApi controller, where the only parameter passed is a string, can I apply a validator attribute for 'Required', or 'String Length'?
This does not seem to work for me...
Example of controller action:
[HttpPost]
[ActionName("GetInventoryDetails")]
public HttpResponseMessage GetInventoryDetails([FromBody][Required][StringLength(20)]string serialNumber)
{
if (ModelState.IsValid == true)
{
var response = Request.CreateResponse(statusCode: HttpStatusCode.OK, value: string.Empty, mediaType: Request.Content.Headers.ContentType);
return response;
}
else
{
var response = Request.CreateResponse(statusCode: HttpStatusCode.BadRequest);
return response;
}
}
when I pass in a string longer than 20 characters ModelState.IsValid is true. Also, if I pass no parameter ModelState.IsValid is also true. In both cases I was expecting ModelState.IsValid to be false.
BTW - if instead I construct a controller action to accept an object instead of a string, and if I place attribute validators on properties of the class then validation works as expected, and ModelState.IsValid shows false. It is only when trying to use attribute validators inline as in my example above where the ModelState.IsValid is showing an unexpected result.