user3567026
user3567026

Reputation: 91

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

Upvotes: 3

Views: 2453

Answers (2)

StepUp
StepUp

Reputation: 38199

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

Upvotes: 3

Jakub
Jakub

Reputation: 1165

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.

Upvotes: 1

Related Questions