英文:
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<ActionResult> UpdateMultiple(List<Employee> employees)
{
if (!ModelState.IsValid || employees.Count < 1 )
{
return BadRequest();
}
}
答案1
得分: 1
看到新增的条件检查(注意你必须将 yourIndividualValidator 更改为实际的验证器)
public async Task<ActionResult> UpdateMultiple(List<Employee> employees)
{
if (!ModelState.IsValid || employees.Count < 1 ||
employees.Any(x => yourIndividualValidator(x) == false)
)
{
return BadRequest();
}
}
英文:
See the added condition check (note that you must change the yourIndividualValidator for the actual one)
public async Task<ActionResult> UpdateMultiple(List<Employee> employees)
{
if (!ModelState.IsValid || employees.Count < 1 ||
employees.Any(x => yourIndividualValidator(x) == false)
)
{
return BadRequest();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论