ValidatorHelper.cs 2.2 KB

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