using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; namespace Infrastructure.Extensions { public static class ModelStateDictionaryExtensions { public static void AddModelError(this ModelStateDictionary modelState, IList validationResults) { foreach (var item in validationResults) { if (item.MemberNames.Any()) { foreach (var key in item.MemberNames) { modelState.AddModelError(key, item.ErrorMessage); } } else { modelState.AddModelError("", item.ErrorMessage); } } } public static object AddModelError(this ModelStateDictionary modelState, string message, string key = "", int code = 0) { modelState.AddModelError(key, message); return new { code, key = string.IsNullOrEmpty(key) ? key : key.Substring(0, 1).ToLower() + key.Substring(1), message }; } public static object AddModelError(this ModelStateDictionary modelState, Expression> expression, string message, int code = 0) { return modelState.AddModelError(message, expression.GetPropertyName(), code); } } }