AOP的作用:把通用处理逻辑提炼到一个单独的地方,其它地方需要调用,添加这个"特性"即可,不需要再次进行编写,比如AOP的过滤、异常处理、权限控制等
一、自定义Attribute
1、项目结构
2、UserModelFiledAttribute代码实例,此类是定义特性
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, Inherited = true)] 2 3 public class UserModelLengthAttribute : Attribute 4 { 5 private int maxLength; 6 7 public UserModelLengthAttribute(int maxLength) 8 { 9 this.maxLength = maxLength; 10 } 11 public int MaxLength { get => maxLength; set => maxLength = value; } 12 }
3、AopHandler类用于实现特性需要处理的逻辑,如本实例验证了字段最大长度,需要引入:using System.Reflection;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public void ValidateLength(object obj) 2 { 3 Type tType = obj.GetType(); 4 var properties = tType.GetProperties(); 5 foreach (var item in properties) 6 { 7 if (!item.IsDefined(typeof(UserModelLengthAttribute), false)) continue; 8 9 var attributes = item.GetCustomAttributes(); 10 foreach (var attributeItem in attributes) 11 { 12 //获取特性的属性值(MaxLength为UserModelFiledAttribute定义的参数) 13 var maxLen = (int)attributeItem.GetType().GetProperty("MaxLength").GetValue(attributeItem); 14 //获取字段属性值 15 var value = item.GetValue(obj) as string; 16 if (string.IsNullOrEmpty(value)) 17 { 18 Console.WriteLine(item.Name + "的值为null"); 19 } 20 else 21 { 22 if (value.Length > maxLen) 23 { 24 Console.WriteLine(item.Name + "的值的长度为" + value.Length + ",超出了范围"); 25 } 26 } 27 } 28 } 29 }
4、UserModel
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class UserModel 2 { 3 public string UserName { get; set; } 4 [UserModelLength(10)]//引用特性 5 public string UserPassword { get; set; } 6 7 [UserModelFiled(true)]//引用特性 8 public string UserSex { get; set; } 9 10 public int Age { get; set; } 11 }
5、使用方式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 var userModel = new UserModel() { UserName = "test", UserPassword = "yxj2222345234234234" }; 2 new AopHandler().ValidateLength(userModel);//调用此函数进行特性效验后执行功能代码
二、使用扩展Attribute
第一种方式有些繁琐,因此可以通过vs自带的特性进行扩展,此实例是通过MVC验证一个登陆功能,通过Login登陆后跳转至Index页面,Index页面调用特性去效验是否登录
1、Login控制器代码
1、Validate特性类
贴代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class LoginAttribute : ActionFilterAttribute, IResultFilter 2 { 3 public override void OnActionExecuting(ActionExecutingContext actionExecutingContext) 4 { 5 if (HttpContext.Current.Request.Cookies["token"]["userid"] == null) 6 { 7 actionExecutingContext.HttpContext.Response.Write("<script>window.parent.location.href='http://localhost:59087/User/Login'</script>"); 8 } 9 base.OnActionExecuting(actionExecutingContext); 10 } 11 }
3、Index调用特性
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 [Login] 2 public ActionResult Index() 3 { 4 return View(); 5 }
参考博客:https://www.cnblogs.com/ldyblogs/p/attribute.html