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

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