c# - 如何处理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."
]
我尝试在操作方法中捕获异常,但由于验证发生在它甚至命中操作方法之前,我如何才能捕获此异常并显示对用户有意义的错误消息。另外,由于错误数组中的键以“$”开头,因此我如何将其与发生错误的实际键/字段一起传递回前端。. 提前致谢
解决方案
您可以指定错误消息链接
[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]
推荐阅读
- .net - 如何在 blazor webassembly 的多个项目中使用相同的登录页面?
- php - PHP:将 X.pdf 连接到所选目录中的 X.png
- reactjs - 里面有没有使用Formik道具
- prolog - 为什么我会收到“单例变量”警告和不正确的结果?
- javascript - app脚本,file.makeCopy创建一个新文件后,如何访问这个新文件
- python - 从 Python 中的文件夹中按顺序读取帧的问题
- perl - 从文本文件中提取某些行,跳过其他行
- python - 根据工作簿的名称向每个 Excel 工作簿添加日期列。使用 python 和熊猫
- assembly - 查找字符串中的子字符串及其位置
- c# - 如何向 xaml 中的绑定添加其他文本(或字符串)