例如,在我的C#模型中,我有
public class Account
{
public int Id { get; set; }
public AccountType AccountType { get; set; }
public string Name { get; set; }
}
注:AccountType
是C#枚举
当我使用Postman测试它时,POST请求如下,
{
"AccountType": "a",
"Name": "John"
}
错误响应为400错误请求
{
"accountType": [
"Error converting value "a" to type 'Models.App.Enum.AccountType'. Path 'AccountType', line 2, position 22."
]
}
现在,我对Name
属性进行了手动验证。
if (string.IsNullOrEmpty(account.Name))
{
return BadRequest("Name is required");
}
但当我使用Postman和POST请求测试它时,如下所示,{"AccountType":"1〃
"名称":"quot;}
错误响应为400错误请求
Name is required
我的问题是如何手动编写Name
验证,以便错误响应格式与AccountType
类似?这样,前端开发人员就可以从标准化的错误响应格式中获得错误消息。或者我应该手动为AccountType
编写验证以与Name
格式匹配吗?
您可以创建匿名对象并将该对象作为结果传递。
return BadRequest(new { Name = new string[] {"Name is Required"} });