一致的输入模型验证错误报告

  • 请求路径:http://xxx/cs/Device/FertilizerGetStatus?gatCode=xxx&deviceId=xxx
  • deviceId无效,导致验证不通过,从而不能正确路由,导致400错误
  • 错误结果
    1. {
    2. "errors": {
    3. "deviceId": [
    4. "The value 'sfsdf' is not valid."
    5. ]
    6. },
    7. "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    8. "title": "One or more validation errors occurred.",
    9. "status": 400,
    10. "traceId": "00-8e5e830bc8e1175a8a2ebc76807a7b7c-1f32aa202f2ce064-00"
    11. }

自定义的Bad Request方法

  • 使用:startup.cs ConfigureServices

    1. services.AddMvc()
    2. .ConfigureApiBehaviorOptions(options =>
    3. {
    4. options.InvalidModelStateResponseFactory = context =>
    5. {
    6. var problems = new CustomBadRequest(context);
    7. return new BadRequestObjectResult(problems);
    8. };
    9. });
  • 自定义类 CustomBadRequest

    1. public class CustomBadRequest : ValidationProblemDetails
    2. {
    3. public CustomBadRequest(ActionContext context)
    4. {
    5. Title = "Invalid arguments to the API";
    6. Detail = "The inputs supplied to the API are invalid";
    7. Status = 400;
    8. ConstructErrorMessages(context);
    9. Type = context.HttpContext.TraceIdentifier;
    10. }
    11. private void ConstructErrorMessages(ActionContext context)
    12. {
    13. foreach (var keyModelStatePair in context.ModelState)
    14. {
    15. var key = keyModelStatePair.Key.Replace("$.", "");
    16. var errors = keyModelStatePair.Value.Errors;
    17. if (errors != null && errors.Count > 0)
    18. {
    19. if (errors.Count == 1)
    20. {
    21. var errorMessage = GetErrorMessage(key, errors[0]);
    22. Errors.Add(key, new[] { errorMessage });
    23. }
    24. else
    25. {
    26. var errorMessages = new string[errors.Count];
    27. for (var i = 0; i < errors.Count; i++)
    28. {
    29. errorMessages[i] = GetErrorMessage(key,errors[i]);
    30. }
    31. Errors.Add(key, errorMessages);
    32. }
    33. }
    34. }
    35. }
    36. string GetErrorMessage(string key, ModelError error)
    37. {
    38. if (error.ErrorMessage != $"The {key} field is required.")
    39. {
    40. return $"The {key} field is badly formed.";
    41. }
    42. return error.ErrorMessage;
    43. }
    44. }