using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Luticate2.Utils.Controllers; using Luticate2.Utils.Dbo.Result; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Luticate2.Utils.Middlewares { public class LuModelStateFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { var descriptor = context.ActionDescriptor as ControllerActionDescriptor; if (descriptor != null) { var parameters = descriptor.MethodInfo.GetParameters(); foreach (var parameter in parameters) { var argument = context.ActionArguments.ContainsKey(parameter.Name) ? context.ActionArguments[parameter.Name] : null; EvaluateValidationAttributes(parameter, argument, context.ModelState); } } if (!context.ModelState.IsValid) { var errors = ""; foreach (var key in context.ModelState.Keys) { var state = context.ModelState[key]; if (state.Errors.Count > 0) { var error = " " + key + ": " + state.Errors.Select(modelError => modelError.ErrorMessage) .Aggregate((s, s1) => s + ", " + s1); errors += error; } } throw new LuResultException(LuResult.Error(LuStatus.InputError, "Validation error:" + errors, "")); } } private void EvaluateValidationAttributes(ParameterInfo parameter, object argument, ModelStateDictionary modelState) { foreach (var attributeData in parameter.CustomAttributes) { var validationAttribute = parameter.GetCustomAttribute(attributeData.AttributeType) as ValidationAttribute; if (validationAttribute != null) { var isValid = validationAttribute.IsValid(argument); if (!isValid) { modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name)); } } } } public void OnActionExecuted(ActionExecutedContext context) { } } }