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

wor*_*dev 5 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
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的 DTO 模型

public class CreateProductDto
{
    [Required(ErrorMessage = "Invalid value")]
    public decimal totalPrice { get; set;}

    public int count { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法从模型绑定错误中自定义文本?我想防止发送敏感信息并向客户提供友好的反馈?

Mof*_*hen 4

您可以从 Startup 类的ConfigureServices 方法中自定义错误消息。详细内容可以查看微软文档

这是一个例子 -

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

您可以阅读博客。