empty object check for ASP.NET Core API request

Viewed 1403

I have a api controller which receives parameter from body like public virtual async Task<ActionResult> TestCommAsync([FromBody] CommRequest commRequest)

The Comm Request object is as follows

 public class CommRequest 
{
    /// <summary>
    /// Gets or sets the value that represents the collection of <see cref="CommunicationHistory"/>
    /// </summary>
    public IEnumerable<commItems> commItemsAll{ get; set; }
}

When I am passing just {} empty object my condition through postman

if(commRequest == null) is not working ..It passes as it is not null.. Need help in proper way checking is null and empty

2 Answers

Try to check whether the property has any item by using Any():

if (commItemsAll != null && commItemsAll.Any()) 
{
    return Ok();
}
return BadRequest();

or shorter version:

if (commItemsAll?.Any() ?? false)
{
    return Ok();
}
return BadRequest();

You should check 'commonItemsAll' for null instead of 'commRequest' . If you send '{}' in body, it means that you send instance (not null) of the model with every property set to null.

Related