小编wor*_*dev的帖子

ASP.NET Core 自定义模型绑定失败时的错误

每当向 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
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的 DTO 模型

public class CreateProductDto
{
    [Required(ErrorMessage = …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-web-api

5
推荐指数
1
解决办法
2002
查看次数

标签 统计

asp.net ×1

asp.net-web-api ×1