【问题标题】:How to handle validation exceptions in asp.net core webapi如何处理asp.net core webapi中的验证异常
【发布时间】:2021-09-14 09:22:56
【问题描述】:

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

//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."
        ]

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

【问题讨论】:

    标签: c# validation asp.net-web-api validationexception


    【解决方案1】:

    您可以指定错误消息link

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

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 2014-06-18
      • 2017-03-29
      • 1970-01-01
      • 2016-12-02
      • 2020-12-16
      • 2011-04-08
      • 2015-09-13
      • 1970-01-01
      相关资源
      最近更新 更多