问题描述
执行操作时,请接受以下参数:
[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")]