微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.NET 5,ASP.NET Blazor 返回 DataAnnotation 错误而不是 JSON 解析器错误

如何解决.NET 5,ASP.NET Blazor 返回 DataAnnotation 错误而不是 JSON 解析器错误

有没有办法获得 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 举报,一经查实,本站将立刻删除。