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

时间:2018-12-09 22:24:57

标签: asp.net asp.net-web-api

无论何时将空值或无效值发送到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; }
}

是否可以通过模型绑定错误来自定义文本?我想防止敏感信息被发送并向客户提供友好的反馈?

1 个答案:

答案 0 :(得分:1)

您可以在ConfigureServices方法中从Startup类自定义错误消息。您可以查看详细信息Microsoft document

这里是一个示例-

services.AddMvc(options =>
            {
                var iStrFactory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
                var L = iStrFactory.Create("ModelBindingMessages", "WebUI"); // Resource file location 
                options.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) => L["The value '{0}' is invalid."]);

                options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) => L["The field {0} must be a number."]);
                options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) => L["A value for the '{0}' property was not provided.", x]);
                options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => L["The value '{0}' is not valid for {1}.", x, y]);
                options.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() => L["A value is required."]);
                options.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) => L["The supplied value is invalid for {0}.", x]);
                options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) => L["Null value is invalid.", x]);
            });

您可以阅读this博客。