ASP.NET 错误数组中的核心空验证字符串条目?

ASP.NET Core empty validation string entry in array of errors?

当我们有一个动作时,接受以下参数:

[FromBody][Range(1, 10)] int hello

当验证失败时,返回的对象有一个空条目,如下所示:

"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3b00401-417ccac45f29647d.",
"errors": {
    "": [
        "hello is required."
    ]
}

}

这是为什么?您能否参考导致此问题的来源?我相信它与反射有关,即它们获取对象的属性,但在我们的例子中它是一个简单的 int/string 对象,而不是自定义类型。

首先可以参考this

您可以看到默认的 BadRequest 响应:

errors": {
    "": [
      "A non-empty request body is required."
    ]

It should be "number": [ "The field number...." but right now it's "" : [ "The field number...,所以响应是默认的响应格式。 如果你想自定义错误,你可以这样做:

public class CustomBadRequest : ValidationProblemDetails
    {
        public CustomBadRequest(ActionContext context)
        {
            Title = "Invalid arguments to the API";
            Detail = "The inputs supplied to the API are invalid";
            Status = 400;
            ConstructErrorMessages(context);
            Type = context.HttpContext.TraceIdentifier;
        }

        private void ConstructErrorMessages(ActionContext context)
        {
            var reader = new StreamReader(context.HttpContext.Request.Body);
            var body = reader.ReadToEndAsync();
            

            
            foreach (var keyModelStatePair in context.ModelState)
            {
                var key = keyModelStatePair.Key;
                if (key == "")
                {
                    Errors.Add("number", new string[] { "nmber is not between 1,10" });
                }
                else
                {
                    Errors.Add("number", new string[] { "this is not number" });
                }
           }
        }

        string GetErrorMessage(ModelError error)
        {
            return string.IsNullOrEmpty(error.ErrorMessage) ?
                "The input was not valid." :
            error.ErrorMessage;
        }
}

在Startup.cs

中修改
services.AddControllersWithViews()
                .ConfigureApiBehaviorOptions(options=>
                {
                    options.InvalidModelStateResponseFactory = contet =>
                    {
                        var problems = new CustomBadRequest(contet);
                        return new BadRequestObjectResult(problems);
                    };
                });

结果:

您可以使用 ModelBinder 属性实现此目的。

例如:

[ModelBinder(Name = "number")]