| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 | 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 error = " " + key + ": " + context.ModelState[key]
                        .Errors.Select(modelError => modelError.ErrorMessage)
                        .Aggregate((s, s1) => s + ", " + s1);
                    errors += error;
                }
                throw new LuResultException(LuResult<object>.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)
        {
        }
    }
}
 |