c# - 有没有办法为默认模型绑定(bind)错误构建自定义错误消息,想要摆脱消息中的行和位置

标签 c# .net asp.net-core

{
    "errors": {
        "price": [
            "Could not convert string to decimal: dasdfasdf. Path 'price', line 3, position 22."
        ],
        "userId": [
            "Could not convert string to integer: hsad. Path 'userId', line 6, position 27."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|bcaa98d957e1c04181000489a0bc4950.9753735a_"
}

我试过自定义模型 Binder ,但我需要它用于模型中的特定属性。我还尝试了 JsonConvert 的属性,但找不到在模型状态中注入(inject)错误消息的方法

最佳答案

您可以通过配置 ApiBehaviorOptionsInvalidModelStateResponseFactory 来自定义 ApiController 的 ModelState 验证器响应,如下所示:

services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = actionContext => 
    {
        var errors = actionContext.ModelState
            .Where(e => e.Value.Errors.Count > 0)
            .Select(e => new Error
            {
            Name = e.Key,
            Message = e.Value.Errors.First().ErrorMessage
            }).ToArray();

        return new BadRequestObjectResult(errors);
    }
});

此外,您还可以阅读有关 ApiController 行为的更多信息 here .

关于c# - 有没有办法为默认模型绑定(bind)错误构建自定义错误消息,想要摆脱消息中的行和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653921/

相关文章:

c# - Selenium - 如何断言该字段等于 0

c# - MVC4 Web API返回带有特殊字符的json propertykey字符串

c# - 使用 Java 解密由 .NET 的 RijndaelManaged 加密的字节

.net - 如何在 NodaTime 中获取 "start of the year/month"?

c# - WPF如何使StackPanel可滚动

asynchronous - .net core 中的异步流下载

c# - 在 dbcontext 中的请求之间存储数据

c# - Visual Studio 2017 缺少 "Add RestAPI Client"

c# - Selenium 通过 XPath 获取元素

c# - AuthorizeRouteView Authorizing 和 NotAuthorized 参数设置