【发布时间】:2019-05-10 20:37:18
【问题描述】:
每当向 ASP.NET Core Web API 端点发送空值或无效值时,我都会尝试应用后端验证,但我不知道如何处理模型绑定失败错误。
在提交无效值时可能从ModelState 收到此错误:totalPrice: ["Could not convert string to decimal: . Path 'totalPrice', line 1, position 71."]
0: "Could not convert string to decimal: . Path 'totalPrice', line 1, position 71." 看起来模型绑定失败并且错误直接显示给客户端。
我有一个非常简单的控制器,上面装饰有ApiController 属性。
[ApiController]
public class ProductsController
{
[HttpPost]
public IActionResult Post([FromBody]CreateProductDto model)
{
model.Id = await service.CreateProduct(model);
return CreatedAtRoute(
routeName: "GetProduct",
routeValues: new { id = model.Id },
value: model
);
}
}
还有我的 DTO 模型
public class CreateProductDto
{
[Required(ErrorMessage = "Invalid value")]
public decimal totalPrice { get; set;}
public int count { get; set; }
}
有没有办法从模型绑定错误中自定义文本?我想阻止发送敏感信息并向客户提供友好的反馈?
【问题讨论】:
-
您收到模型绑定错误。您可以注册全局错误过滤器并根据其类型处理错误。
-
我推荐一个自定义模型绑定器。这需要更多的工作,但可以为您提供更多的灵活性。