继续上一篇
上一篇,从core方式实现了一个Rabbitmq发送队列消息的接口,我们现在需要在模型验证里面加入验证失败就发送消息的部分
[AttributeUsage(AttributeTargets.Class)]
public class ValidateBaseAttribute:ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { return ValidationResult.Success; } }
这个验证特性打上之后,只要模型验证就触发
转到 ValidationContext 里面
在ValidateBaseAttribute内修改如下
[AttributeUsage(AttributeTargets.Class)] public class ValidateBaseAttribute:ValidationAttribute { public Type Type { get; set; } public string FunName { get; set; } public ValidateBaseAttribute() { } public ValidateBaseAttribute(Type type, string funName) { Type = type; FunName = funName; } private bool ExecuteMethod(Type type, string funName,object value) { if (type == null || string.IsNullOrWhiteSpace(funName)) return false; try { var instance = Activator.CreateInstance(type); var method = type.GetMethod(funName); return (bool)method.Invoke(instance, new[] { value }); } catch { return false; } } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var validate = ExecuteMethod(Type, FunName, value); if (validate) { var remoteSend = validationContext.GetService(typeof(IRemoteSend)) as IRemoteSend; if (remoteSend != null) { remoteSend.Send(value);
return new ValidationResult("验证失败"); } } return ValidationResult.Success; } }
在默认的ValuesController内增加方法
[HttpGet("Check")] public User Check([FromQuery]User user) { return user; }
我们修改以下User类
//增加一个验证特性 [ValidateBase(typeof(ValidateClass), "IsValidateUser")]
public class ValidateClass { public bool IsValidateUser(User user) { return user.Name.Equals("admin", StringComparison.InvariantCultureIgnoreCase) || user.Account.Equals("admin", StringComparison.InvariantCultureIgnoreCase); } }
只要用户名或者账号为admin
你以为这样就完了?No,模型验证要触发,必须有一个模型验证触发的过滤器
public class ModelFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { string errorMessage = string.Empty; var ErrorsModel = context.ModelState.Values.Where(item => { return item.Errors.Count > 0; }).ToList().FirstOrDefault(); if (ErrorsModel != null) { errorMessage = ErrorsModel.Errors[0].ErrorMessage; } context.Result = new JsonResult(new { status = -1, msg = errorMessage }); return; } } }
在ConfigureServices内的
//services.AddMvc(); services.AddMvc(options => options.Filters.Add<ModelFilter>());
运行起来测试一下