12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Text;
- namespace TEAMModelOS.SDK
- {
- public static class ValidatorHelper
- {
- public static ValidResult IsValid(this Object obj) {
- ValidResult result = new ValidResult();
- try {
- var context = new ValidationContext(obj, null, null);
- var results = new List<ValidationResult>();
- if (Validator.TryValidateObject(obj, context, results, true))
- {
- result.isVaild = true;
- }
- else
- {
- List<(string msg, string name)> error = new List<(string msg, string name)>();
- foreach (var validationResult in results)
- {
- if (validationResult.MemberNames != null && validationResult.MemberNames.Count()>0) {
- validationResult.MemberNames.ToList().ForEach(x => {
- error.Add((validationResult.ErrorMessage, x));
- });
- }
- }
- result.errors = new Dictionary<string, IEnumerable<string>>();
- error.GroupBy(x => x.name).ToList().ForEach(z => {
- result.errors.Add(z.Key, z.ToList().Select(x => x.msg));
- });
- }
- } catch (Exception ex) {
- result.isVaild = false;
- result.errors = new Dictionary<string, IEnumerable<string>>();
- result.errors.Add("InternalError", new List<string> { ex.Message });
- }
- return result;
- }
-
- }
- public class ValidResult
- {
- public string traceId { get; set; } = Guid.NewGuid().ToString();
- public string type { get; set; } = "https://tools.ietf.org/html/rfc7231#section-6.5.1";
- public string title { get; set; } = "One or more validation errors occurred.";
- public int status { get; set; } = 400;
- public bool isVaild { get; set; }
- public Dictionary<string, IEnumerable<string>> errors { get; set; }
- }
- }
|