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.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 state = context.ModelState[key];
  31. if (state.Errors.Count > 0)
  32. {
  33. var error = " " + key + ": " + state.Errors.Select(modelError => modelError.ErrorMessage)
  34. .Aggregate((s, s1) => s + ", " + s1);
  35. errors += error;
  36. }
  37. }
  38. throw new LuResultException(LuResult<object>.Error(LuStatus.InputError, "Validation error:" + errors, ""));
  39. }
  40. }
  41. private void EvaluateValidationAttributes(ParameterInfo parameter, object argument, ModelStateDictionary modelState)
  42. {
  43. foreach (var attributeData in parameter.CustomAttributes)
  44. {
  45. var validationAttribute = parameter.GetCustomAttribute(attributeData.AttributeType) as ValidationAttribute;
  46. if (validationAttribute != null)
  47. {
  48. var isValid = validationAttribute.IsValid(argument);
  49. if (!isValid)
  50. {
  51. modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name));
  52. }
  53. }
  54. }
  55. }
  56. public void OnActionExecuted(ActionExecutedContext context)
  57. {
  58. }
  59. }
  60. }