/// <summary> /// 参数模型检验过滤器 NetCore版 /// </summary> public class ParaModelValidateAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { //本方法的所有参数描述符 IList<ParameterDescriptor> actionParameters = filterContext.ActionDescriptor.Parameters; //只有这个方法需要参数的时候才进行校验 if (actionParameters.Count != 0) { dynamic paraModel = filterContext.ActionArguments.FirstOrDefault().Value; ParaModelValidateHelper.Validate(paraModel); } } }
public static class ParaModelValidateHelper { /// <summary> /// 参数模型校验 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static void Validate<T>(T entity) where T : class { Type type = entity.GetType(); PropertyInfo[] properties = type.GetProperties(); //循环模型的所有参数 foreach (var item in properties) { //校验必填参数 if (item.IsDefined(typeof(RequiredAttribute), true))//判断该参数是否有Required特性 { var value = item.GetValue(entity);//获取值 if (value == null || string.IsNullOrWhiteSpace(value.ToString())) { throw new Exception(string.Format("缺少必填参数{0}", item.Name)); } } //增加其他类型的校验的话接着写IF //System.ComponentModel.DataAnnotations } } }