如何为 Web API 中的列表执行模型验证

huangapple go评论72阅读模式
英文:

How to do model validation for list in Web API

问题

我有一个在Web API中的控制器,它接受我的模型类的列表。在处理数据库请求之前,我需要验证它。我知道如何验证单个模型,但在模型的列表上卡住了。以下是我的代码。

public async Task<ActionResult> UpdateMultiple(List<Employee> employees)
{
    if (!ModelState.IsValid || employees.Count < 1)
    {
        return BadRequest();
    }
}
英文:

I have controller in Web API which is accepting a list of my model class. I need to validate it before processing for DB request. I know how to do it for single model but stuck on list of model.
Below is my code for it.

public async Task&lt;ActionResult&gt; UpdateMultiple(List&lt;Employee&gt; employees)
{
if (!ModelState.IsValid || employees.Count &lt; 1 )
                {
                     return BadRequest();
                }
}

答案1

得分: 1

看到新增的条件检查(注意你必须将 yourIndividualValidator 更改为实际的验证器)

public async Task&lt;ActionResult&gt; UpdateMultiple(List&lt;Employee&gt; employees)
{
    if (!ModelState.IsValid || employees.Count &lt; 1 || 
        employees.Any(x =&gt; yourIndividualValidator(x) == false)
         )
         {
             return BadRequest();
         }
}
英文:

See the added condition check (note that you must change the yourIndividualValidator for the actual one)

public async Task&lt;ActionResult&gt; UpdateMultiple(List&lt;Employee&gt; employees)
{
if (!ModelState.IsValid || employees.Count &lt; 1 || 
    employees.Any(x =&gt; yourIndividualValidator(x) == false)
     )
     {
         return BadRequest();
     }
}

huangapple
  • 本文由 发表于 2023年3月9日 22:58:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定