ValidatorHelper.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.Linq;
  6. using System.Text;
  7. namespace TEAMModelOS.SDK
  8. {
  9. public static class ValidatorHelper
  10. {
  11. public static ValidResult Valid(this Object obj) {
  12. ValidResult result = new ValidResult();
  13. var list = obj as IEnumerable;
  14. if (list != null)
  15. {
  16. foreach (var item in list)
  17. {
  18. var validationContext = new ValidationContext(item);
  19. var validationResults = new List<ValidationResult>();
  20. var isItemValid = Validator.TryValidateObject(item, validationContext, validationResults, true);
  21. result.isVaild = isItemValid;
  22. }
  23. }
  24. else {
  25. try
  26. {
  27. var context = new ValidationContext(obj, null, null);
  28. var results = new List<ValidationResult>();
  29. if (Validator.TryValidateObject(obj, context, results, true))
  30. {
  31. result.isVaild = true;
  32. }
  33. else
  34. {
  35. List<(string msg, string name)> error = new List<(string msg, string name)>();
  36. foreach (var validationResult in results)
  37. {
  38. if (validationResult.MemberNames != null && validationResult.MemberNames.Count() > 0)
  39. {
  40. validationResult.MemberNames.ToList().ForEach(x => {
  41. error.Add((validationResult.ErrorMessage, x));
  42. });
  43. }
  44. }
  45. result.errors = new Dictionary<string, IEnumerable<string>>();
  46. error.GroupBy(x => x.name).ToList().ForEach(z => {
  47. result.errors.Add(z.Key, z.ToList().Select(x => x.msg));
  48. });
  49. }
  50. }
  51. catch (Exception ex)
  52. {
  53. result.isVaild = false;
  54. result.errors = new Dictionary<string, IEnumerable<string>>();
  55. result.errors.Add("InternalError", new List<string> { ex.Message });
  56. }
  57. }
  58. return result;
  59. }
  60. }
  61. public class ValidResult
  62. {
  63. public string traceId { get; set; } = Guid.NewGuid().ToString();
  64. public string type { get; set; } = "https://tools.ietf.org/html/rfc7231#section-6.5.1";
  65. public string title { get; set; } = "One or more validation errors occurred.";
  66. public int status { get; set; } = 400;
  67. public bool isVaild { get; set; }
  68. public Dictionary<string, IEnumerable<string>> errors { get; set; }
  69. }
  70. }