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

问题描述

执行操作时,请接受以下参数:

[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);
                    };
                });

结果: enter image description here enter image description here

,

您可以使用ModelBinder属性来实现。

例如:

[ModelBinder(Name = "number")]

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...