The Web API project is created in ASP.NET Core 2.2.
I have a POST
method which accepts a custom class as parameter:
public async Task<IActionResult> MyWebMethod(Id id,
[FromBody] IReadOnlyCollection<MyCustomClass> instances)
{
// Process the data
return CreatedAtRoute("GetMyCollection",
new
{
id,
myIds = "someString";
},
responsesObject);
}
The code works fine when it receives a proper instance.
If the method receives any null parameter or an empty object from the client request, then I need to send back a 422 response to the client (422 Unprocessable Entity).
I placed some code within the method to handle such scenarios:
if (instances == null || instances.Count == 0)
{
return StatusCode(Convert.ToInt32(HttpStatusCode.UnprocessableEntity), instances);
}
But the issue is: whenever a null or an empty object is passed to the Web API method, the method does not get hit (when I try to debug the method).
What would be the best way to handle such request and send back a 422 response back to client?