AOP的使用

AOP的作用:把通用处理逻辑提炼到一个单独的地方,其它地方需要调用,添加这个"特性"即可,不需要再次进行编写,比如AOP的过滤、异常处理、权限控制等

一、自定义Attribute

1、项目结构

2、UserModelFiledAttribute代码实例,此类是定义特性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, Inherited = true)]

public class UserModelLengthAttribute : Attribute
{
private int maxLength;

public UserModelLengthAttribute(int maxLength)
{
this.maxLength = maxLength;
}
public int MaxLength { get => maxLength; set => maxLength = value; }
}

3、AopHandler类用于实现特性需要处理的逻辑,如本实例验证了字段最大长度,需要引入:using System.Reflection;

public void ValidateLength(object obj)
{
Type tType = obj.GetType();
var properties = tType.GetProperties();
foreach (var item in properties)
{
if (!item.IsDefined(typeof(UserModelLengthAttribute), false)) continue;

var attributes = item.GetCustomAttributes();
foreach (var attributeItem in attributes)
{
//获取特性的属性值(MaxLength为UserModelFiledAttribute定义的参数)
var maxLen = (int)attributeItem.GetType().GetProperty("MaxLength").GetValue(attributeItem);
//获取字段属性值
var value = item.GetValue(obj) as string;
if (string.IsNullOrEmpty(value))
{
Console.WriteLine(item.Name + "的值为null");
}
else
{
if (value.Length > maxLen)
{
Console.WriteLine(item.Name + "的值的长度为" + value.Length + ",超出了范围");
}
}
}
}
}

4、UserModel

public class UserModel
{
public string UserName { get; set; }
[UserModelLength(10)]//引用特性
public string UserPassword { get; set; }

[UserModelFiled(true)]//引用特性
public string UserSex { get; set; }

public int Age { get; set; }
}

5、使用方式:

var userModel = new UserModel() { UserName = "test", UserPassword = "yxj2222345234234234" };
new AopHandler().ValidateLength(userModel);//调用此函数进行特性效验后执行功能代码

二、使用扩展Attribute

第一种方式有些繁琐,因此可以通过vs自带的特性进行扩展,此实例是通过MVC验证一个登陆功能,通过Login登陆后跳转至Index页面,Index页面调用特性去效验是否登录

1、Login控制器代码

1、Validate特性类

 

贴代码:

public class LoginAttribute : ActionFilterAttribute, IResultFilter
{
public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
{
if (HttpContext.Current.Request.Cookies["token"]["userid"] == null)
{
actionExecutingContext.HttpContext.Response.Write("<script>window.parent.location.href='http://localhost:59087/User/Login'</script>");
}
base.OnActionExecuting(actionExecutingContext);
}
}

3、Index调用特性

[Login]
public ActionResult Index()
{
return View();
}

参考博客:https://www.cnblogs.com/ldyblogs/p/attribute.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章