问题描述
有没有办法获得 DataAnnotation 错误而不是 JSON 解析器错误?
[RegularExpression(@"^(?i)(true|false)$",ErrorMessage = "{0} must be either 'true' or 'false'")]
public bool Isstudent { get; set; }
[required]
[StringLength(50)]
[DataType(DataType.Text)]
[RegularExpression(@"^[A-Z]+[a-zA-Z\-]*$",ErrorMessage = "FirstName may only contain letters,numbers and dashes.")]
[display(Name = "First Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[displayFormat(DataFormatString = "{0:dd-MM-yyyy}",ApplyFormatInEditMode = true)]
[display(Name = "Date Started")]
public DateTime? DateStarted { get; set; }
我的控制器:
[Route("api/[controller]")]
[ApiController]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public class PeopleController : Controller
{
//Removed for brevity
[Authorize]
[HttpPost("personupload")]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
[ProducesResponseType(401)]
public IActionResult CreatePersonBatch([FromBody] IEnumerable<PersonImport> people)
{
//I understand this is not necessary
//Trying to see if it makes a difference. It does not.
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Goes on to create data table
}
}
当我用邮递员发送以下内容时,
[
{
"LocationId": 0,"RankId": 0,"Isstudent": a,"IsProspect": true,"Isvendor": true,"IsAppUser": true,"FirstName": "string","LastName": "<Student>","BirthDate": "2021-03-14","Gender": "string","UniformTopSize": "string","UniformBottomSize": "string","BeltSize": "string","DateStarted": "Now","DateLastAttended": "2021-03-14","IsHoh": true
}
]
我收到以下回复:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1","title": "One or more validation errors occurred.","status": 400,"traceId": "00-f2bde8fdc701de458f1d86297b7e4813-bdd66281fab85348-00","errors": {
"$[0].Isstudent": [
"The JSON value Could not be converted to System.Boolean. Path: $[0].Isstudent | LineNumber: 4 | BytePositionInLine: 20."
]
}
}
JSON 解析器似乎为它遇到的第一个错误返回了一条不友好的错误消息。我想像 DataAnnotation 错误一样向 API 用户返回友好(更)错误的列表。我似乎不知道如何抢占 JSON 解析器。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)