对ASP.NET Core API请求进行空对象检查。

问题描述 投票:0回答:2

我有一个api控制器,它从body中接收参数,如 public virtual async Task<ActionResult> TestCommAsync([FromBody] CommRequest commRequest)

通信请求对象如下

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

当我通过postman只传递{}空对象时,我的条件是

if(commRequest == null)不工作...它通过了,因为它不是空的。需要帮助以正确的方式检查是否为空和空。

c# asp.net api web core
2个回答
3
投票

试着用以下方法检查该属性是否有任何项目 Any():

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

或更短的版本。

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

1
投票

你应该检查'commonItemsAll'是否为空,而不是'commRequest'。如果你在body中发送'{}',这意味着你发送了模型的实例(而不是null),每个属性都设置为null。

© www.soinside.com 2019 - 2024. All rights reserved.