【问题标题】:empty object check for ASP.NET Core API request空对象检查 ASP.NET Core API 请求
【发布时间】:2020-08-22 22:27:12
【问题描述】:

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

Comm Request对象如下

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

当我通过邮递员传递 {} 空对象时,我的条件

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

【问题讨论】:

  • public virtual async 为什么virtual 用于 API?

标签: c# api asp.net-core web


【解决方案1】:

尝试使用Any()检查属性是否有项目:

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

或更短的版本:

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

【讨论】:

  • Any 可能比Count 更好,因为它可以省去遍历序列中的所有项目。
  • @Sean 你是绝对正确的!感谢您的宝贵意见!我已编辑回复!
【解决方案2】:

您应该检查 'commonItemsAll' 是否为 null 而不是 'commRequest' 。如果您在正文中发送“{}”,则表示您发送模型的实例(非 null),每个属性都设置为 null。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2021-05-24
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多