How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?
I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).
When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".
Classes
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
public HttpResponseMessage Squirrels(SquirrelsRequest model)
{
// model already parsed by the time breakpoint reaches here and non-convertable elements already stripped
...
...
...
SquirrelsResponse results = Targeting.SearchForSquirrels(model);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
public class SquirrelsRequest
{
public SquirrelsRequest() {}
public List<long> PreferredNutTypes { get; set; } = new List<long>();
public GeographySearch geographySearch { get; set; } = new GeographySearch();
}
public class GeographySearch
{
public GeographySearch() {}
public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
public List<long> GeographyIDs { get; set; } = new List<long>();
}
public enum BooleanOperator
{
AND,
OR
}
Examples:
//"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
{
"PreferredNutTypes": [34,21],
"GeographySearch": {
"Operator": 1,
"GeographyIDs": ["Toronto"]
},
}
// This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
new SquirrelsRequest()
{
PreferredNutTypes = new List<long>() { 34, 21 },
GeographySearch = new GeographySearch()
{
Operator = 1
GeographyIDs = new List<long>()
}
}
Expectations:
Things I've attempted:
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value \"sonali7678687\" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."
... surely there must be a better way of validating?
UPDATE 1: Rephrased question to make explanation and intent more clear.