0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sm101
  • 562
  • 3
  • 10
  • 28

1 Answers1

0

Declare instances as default parameter and then check for null

public async Task<IActionResult> MyWebMethod(Id id,
        [FromBody] IReadOnlyCollection<MyCustomClass> instances = null)
{

    if (instances == null || instances.Count == 0)
    {
        return StatusCode(Convert.ToInt32(HttpStatusCode.UnprocessableEntity), instances);
    }
    //Proccess the data
}
as-if-i-code
  • 2,103
  • 1
  • 10
  • 19
  • I tried this..still ASP.NET Core throws an exception. It doesn't even hit the method. Can you please help on how to set it up – sm101 Jul 13 '20 at 09:03
  • Then specify `route` attribute for method. Try one of following 2 approaches `[Route("controllerName/MyWebMethod/{id}/{instances?}")]` or `[Route("controllerName/MyWebMethod/{id}/{instances=null}")]` – as-if-i-code Jul 13 '20 at 10:30
  • I'm getting a MethodNotAllowed status code in this case. Is it something I missed – sm101 Jul 13 '20 at 14:34
  • Have you added `[HttpPost]` attribute for your method? – as-if-i-code Jul 13 '20 at 14:39
  • Yes [HttpPost] attribute is there – sm101 Jul 13 '20 at 15:25
  • multiple solutions listed [here](https://stackoverflow.com/questions/15718741/405-method-not-allowed-web-api), try them. – as-if-i-code Jul 14 '20 at 05:05