首页 > 解决方案 > 如何处理asp.net core webapi中的验证异常

问题描述

我有一个处理 http post 请求的 api 控制器,如下所示

//controller
[Route("api/[controller]")]
[ApiController]
public class SomeController : ControllerBase
{
    //constructor here//

    [HttpPost]
    public async Task<IActionResult> Post(SomeModel model)
    {
        await handleData(model)  ;
        return Ok();
    }
}

//Model
public class SomeModel
{
    [Required]
    public string SomeProperty {get; set;}
}

出于测试目的,当我尝试在发布请求中传递布尔值而不是字符串时,服务器响应错误

"$.field": [
            "The JSON value could not be converted to System.String. Path: $.field| LineNumber: 2 | BytePositionInLine: 16."
        ]

我尝试在操作方法中捕获异常,但由于验证发生在它甚至命中操作方法之前,我如何才能捕获此异常并显示对用户有意义的错误消息。另外,由于错误数组中的键以“$”开头,因此我如何将其与发生错误的实际键/字段一起传递回前端。. 提前致谢

标签: c#validationasp.net-web-apivalidationexception

解决方案


您可以指定错误消息链接

[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]

推荐阅读