一致的输入模型验证错误报告
- 请求路径:http://xxx/cs/Device/FertilizerGetStatus?gatCode=xxx&deviceId=xxx
- deviceId无效,导致验证不通过,从而不能正确路由,导致400错误
- 错误结果
{
"errors": {
"deviceId": [
"The value 'sfsdf' is not valid."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-8e5e830bc8e1175a8a2ebc76807a7b7c-1f32aa202f2ce064-00"
}
自定义的Bad Request方法
使用:startup.cs ConfigureServices
services.AddMvc()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var problems = new CustomBadRequest(context);
return new BadRequestObjectResult(problems);
};
});
自定义类 CustomBadRequest
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)
{
foreach (var keyModelStatePair in context.ModelState)
{
var key = keyModelStatePair.Key.Replace("$.", "");
var errors = keyModelStatePair.Value.Errors;
if (errors != null && errors.Count > 0)
{
if (errors.Count == 1)
{
var errorMessage = GetErrorMessage(key, errors[0]);
Errors.Add(key, new[] { errorMessage });
}
else
{
var errorMessages = new string[errors.Count];
for (var i = 0; i < errors.Count; i++)
{
errorMessages[i] = GetErrorMessage(key,errors[i]);
}
Errors.Add(key, errorMessages);
}
}
}
}
string GetErrorMessage(string key, ModelError error)
{
if (error.ErrorMessage != $"The {key} field is required.")
{
return $"The {key} field is badly formed.";
}
return error.ErrorMessage;
}
}