using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Linq.Expressions; namespace Infrastructure.Extensions { public static class ModelStateDictionaryExtensions { public static void AddModelError(this ModelStateDictionary modelState, IList validationResults) { if (modelState is null) { throw new ArgumentNullException(nameof(modelState)); } if (validationResults is null) { throw new ArgumentNullException(nameof(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) { if (modelState is null) { throw new ArgumentNullException(nameof(modelState)); } modelState.AddModelError(key, message); return new { code, key = string.IsNullOrEmpty(key) ? key : key.Substring(0, 1).ToLower(CultureInfo.InvariantCulture) + 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); } } }