You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuModelStateFilter.cs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.ComponentModel.DataAnnotations;
  2. using System.Linq;
  3. using System.Reflection;
  4. using Luticate2.Utils.Controllers;
  5. using Luticate2.Utils.Dbo.Result;
  6. using Microsoft.AspNetCore.Mvc.Controllers;
  7. using Microsoft.AspNetCore.Mvc.Filters;
  8. using Microsoft.AspNetCore.Mvc.ModelBinding;
  9. namespace Luticate2.Utils.Middlewares
  10. {
  11. public class LuModelStateFilter : IActionFilter
  12. {
  13. public void OnActionExecuting(ActionExecutingContext context)
  14. {
  15. var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
  16. if (descriptor != null)
  17. {
  18. var parameters = descriptor.MethodInfo.GetParameters();
  19. foreach (var parameter in parameters)
  20. {
  21. var argument = context.ActionArguments.ContainsKey(parameter.Name) ? context.ActionArguments[parameter.Name] : null;
  22. EvaluateValidationAttributes(parameter, argument, context.ModelState);
  23. }
  24. }
  25. if (!context.ModelState.IsValid)
  26. {
  27. var errors = "";
  28. foreach (var key in context.ModelState.Keys)
  29. {
  30. var error = " " + key + ": " + context.ModelState[key]
  31. .Errors.Select(modelError => modelError.ErrorMessage)
  32. .Aggregate((s, s1) => s + ", " + s1);
  33. errors += error;
  34. }
  35. throw new LuResultException(LuResult<object>.Error(LuStatus.InputError, "Validation error:" + errors, ""));
  36. }
  37. }
  38. private void EvaluateValidationAttributes(ParameterInfo parameter, object argument, ModelStateDictionary modelState)
  39. {
  40. foreach (var attributeData in parameter.CustomAttributes)
  41. {
  42. var validationAttribute = parameter.GetCustomAttribute(attributeData.AttributeType) as ValidationAttribute;
  43. if (validationAttribute != null)
  44. {
  45. var isValid = validationAttribute.IsValid(argument);
  46. if (!isValid)
  47. {
  48. modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name));
  49. }
  50. }
  51. }
  52. }
  53. public void OnActionExecuted(ActionExecutedContext context)
  54. {
  55. }
  56. }
  57. }