Search code examples
c#asp.net-core

Empty object check for ASP.NET Core API request


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


Solution

  • 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();