• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#自定义属性Attribute

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

自定义属性

    /// <summary>
    /// 脱敏属性
    /// </summary>
    public class SensitiveAttribute:Attribute
    {
        #region Fields
        public SensitiveType SensitiveType { get; set; }

        /// <summary>
        /// 开始位置
        /// </summary>
        public int Start { get; set; }

        /// <summary>
        /// 长度
        /// </summary>
        public int Len { get; set; }

        /// <summary>
        /// 敏感字符替换
        /// </summary>
        public string SensitiveReChar { get; set; }

        #endregion

        #region Constructors and Destructors

        public SensitiveAttribute()
        {
            this.Start = 1;
            this.Len = 2;
            this.SensitiveReChar = "*";
        }

        public SensitiveAttribute(SensitiveType type = SensitiveType.IdNumber,int start = 1,int len = 5,string sensitiveReChar = "*")
        {
            this.SensitiveType = type;
            this.Start = start;
            this.Len = len;
            this.SensitiveReChar = sensitiveReChar;
        }
        #endregion

        #region Public Methods and Operators

        #endregion
    }

    /// <summary>
    /// 类型
    /// </summary>
    public enum SensitiveType
    {
        IdNumber,
        Name
    }
View Code

类:

    /// <summary>
    /// 
    /// </summary>
    public class UserInfo
    {
        public string Code { get; set; }

        public string Name { get; set; }


        [Sensitive]
        public string Phone { get; set; }

        [Sensitive(SensitiveType.Name,Len = 3)]
        public string IdCard { get; set; }
    }
View Code

获取属性

    public static class CustomAttributeHelper
    {
        #region MyRegion

        ///// <summary>
        ///// Cache Data
        ///// </summary>
        //private static readonly Dictionary<string, string> Cache = new Dictionary<string, string>();

        ///// <summary>
        ///// 获取CustomAttribute Value
        ///// </summary>
        ///// <typeparam name="T">Attribute的子类型</typeparam>
        ///// <param name="sourceType">头部标有CustomAttribute类的类型</param>
        ///// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
        ///// <returns>返回Attribute的值,没有则返回null</returns>
        //public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction) where T : Attribute
        //{
        //    return GetAttributeValue(sourceType, attributeValueAction, null);
        //}

        ///// <summary>
        ///// 获取CustomAttribute Value
        ///// </summary>
        ///// <typeparam name="T">Attribute的子类型</typeparam>
        ///// <param name="sourceType">头部标有CustomAttribute类的类型</param>
        ///// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
        ///// <param name="name">field name或property name</param>
        ///// <returns>返回Attribute的值,没有则返回null</returns>
        //public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction,
        //    string name) where T : Attribute
        //{
        //    return GetAttributeValue(sourceType, attributeValueAction, name);
        //}

        //private static string GetAttributeValue<T>(Type sourceType, Func<T, string> attributeValueAction,
        //    string name) where T : Attribute
        //{
        //    var key = BuildKey(sourceType, name);
        //    if (!Cache.ContainsKey(key))
        //    {
        //        CacheAttributeValue(sourceType, attributeValueAction, name);
        //    }

        //    return Cache[key];
        //}

        ///// <summary>
        ///// 缓存Attribute Value
        ///// </summary>
        //private static void CacheAttributeValue<T>(Type type,
        //    Func<T, string> attributeValueAction, string name)
        //{
        //    var key = BuildKey(type, name);

        //    var value = GetValue(type, attributeValueAction, name);

        //    lock (key + "_attributeValueLockKey")
        //    {
        //        if (!Cache.ContainsKey(key))
        //        {
        //            Cache[key] = value;
        //        }
        //    }
        //}

        //private static string GetValue<T>(Type type,
        //    Func<T, string> attributeValueAction, string name)
        //{
        //    object attribute = null;
        //    if (string.IsNullOrEmpty(name))
        //    {
        //        attribute =
        //            type.GetCustomAttributes(typeof(T), false).FirstOrDefault();
        //    }
        //    else
        //    {
        //        var propertyInfo = type.GetProperty(name);
        //        if (propertyInfo != null)
        //        {
        //            attribute =
        //                propertyInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
        //        }

        //        var fieldInfo = type.GetField(name);
        //        if (fieldInfo != null)
        //        {
        //            attribute = fieldInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
        //        }
        //    }

        //    return attribute == null ? null : attributeValueAction((T)attribute);
        //}

        ///// <summary>
        ///// 缓存Collection Name Key
        ///// </summary>
        //private static string BuildKey(Type type, string name)
        //{
        //    if (string.IsNullOrEmpty(name))
        //    {
        //        return type.FullName;
        //    }

        //    return type.FullName + "." + name;
        //}

        #endregion

        public static List<T> GetSensitiveResult<T>(List<T> source) where T : class
        {
            PropertyInfo[] pro = (typeof(T)).GetProperties();

            if (pro.Count() == 0)
            {
                return source;
            }
            SensitiveAttribute sensitive = new SensitiveAttribute();
            var customProper = (typeof(T)).GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
            foreach (var sou in source)
            {
                foreach (var item in customProper)
                {
                    var itemValue = item.GetValue(sou, null);
                    if (null!= itemValue)
                    {
                        var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                        var sensitiveAttr = (attrName as SensitiveAttribute);
                        string strSenChar = sensitiveAttr.SensitiveReChar;
                        for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                        {
                            strSenChar += sensitiveAttr.SensitiveReChar;
                        }
                        item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);
                    }

                }
                //foreach (var item in pro)
                //{
                //    var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                //    var attrValue = sou.GetType().GetProperty(item.Name);

                //    if (attrName != null)
                //    {
                //        var itemValue = item.GetValue(sou,null);
                //        if (itemValue != null)
                //        {
                //            //item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(3, 6), "******"), null);
                //        }
                //    }
                //}
            }

            return source;

        }
    }
View Code

 

    /// <summary>
    /// 自定义属性
    /// </summary>
    public static class CustomAttributeHelper
    {
        public static List<T> GetSensitiveResult<T>(List<T> source) where T : class
        {
            var customProper = (typeof(T)).GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
            if (!customProper.Any())
            {
                return source;
            }
            SensitiveAttribute sensitive = new SensitiveAttribute();
            foreach (var sou in source)
            {
                foreach (var item in customProper)
                {
                    var itemValue = item.GetValue(sou, null);
                    if (null!= itemValue)
                    {
                        var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                        var sensitiveAttr = (attrName as SensitiveAttribute);
                        string strSenChar = sensitiveAttr.SensitiveReChar;
                        for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                        {
                            strSenChar += sensitiveAttr.SensitiveReChar;
                        }
                        item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);
                    }

                }
            }

            return source;
        }
            
        /// <summary>
        /// 脱敏属性结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static T GetSensitiveResult<T>(T source) where T : class
        {
            var customProper = (typeof(T)).GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
            if (!customProper.Any())
            {
                return source;
            }
            SensitiveAttribute sensitive = new SensitiveAttribute();
            foreach (var item in customProper)
            {
                var itemValue = item.GetValue(source, null);
                if (null != itemValue)
                {
                    var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                    var sensitiveAttr = (attrName as SensitiveAttribute);
                    string strSenChar = sensitiveAttr.SensitiveReChar;
                    for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                    {
                        strSenChar += sensitiveAttr.SensitiveReChar;
                    }
                    item.SetValue(source, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);
                }
            }

            return source;
        }


        private static  int SIZE = 6;
        private static  string SYMBOL = "*";

        public static String toConceal(String value)
        {
            if (null == value || "".Equals(value))
            {
                return value;
            }
            int len = value.Length;
            int pamaone = len / 2;
            int pamatwo = pamaone - 1;
            int pamathree = len % 2;
            StringBuilder stringBuilder = new StringBuilder();
            if (len <= 2)
            {
                if (pamathree == 1)
                {
                    return SYMBOL;
                }
                stringBuilder.Append(SYMBOL);
                stringBuilder.Append(value.Substring(len - 1,1));
            }
            else
            {
                if (pamatwo <= 0)
                {
                    stringBuilder.Append(value.Substring(0, 1));
                    stringBuilder.Append(SYMBOL);
                    stringBuilder.Append(value.Substring(len - 1, 1));

                }
                else if (pamatwo >= SIZE / 2 && SIZE + 1 != len)
                {
                    int pamafive = (len - SIZE) / 2;
                    stringBuilder.Append(value.Substring(0, pamafive));
                    for (int i = 0; i < SIZE; i++)
                    {
                        stringBuilder.Append(SYMBOL);
                    }
                    if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0))
                    {
                        stringBuilder.Append(value.Substring(len - pamafive));
                    }
                    else
                    {
                        stringBuilder.Append(value.Substring(len - (pamafive + 1)));
                    }
                }
                else
                {
                    int pamafour = len - 2;
                    stringBuilder.Append(value.Substring(0, 1));
                    for (int i = 0; i < pamafour; i++)
                    {
                        stringBuilder.Append(SYMBOL);
                    }
                    stringBuilder.Append(value.Substring(len - 1));
                }
            }
            return stringBuilder.ToString();

        }

    }
View Code

自定义过滤器:

    public class SensitiveCustomAttribute:ActionFilterAttribute
    {
        
        //&& (objectContent.Value.GetType().BaseType == typeof(Parm) || objectContent.Value.GetType() == typeof(Parm))

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var objectContent = actionExecutedContext.Response.Content as ObjectContent;
            if (objectContent != null && objectContent.Value != null)
            {
                var res = objectContent.Value.GetType().GetProperty("Data");
                if (null!= res)
                {
                    var resVal =  res.GetValue(objectContent.Value, null);
                    if (resVal.GetType().IsGenericType)
                    {
                        foreach (var sou in (IEnumerable)resVal)
                        {
                            var customProper = sou.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
                            foreach (var item in customProper)
                            {
                                var itemValue = item.GetValue(sou, null);
                                if (null != itemValue)
                                {
                                    var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                                    var sensitiveAttr = (attrName as SensitiveAttribute);
                                    string strSenChar = sensitiveAttr.SensitiveReChar;
                                    for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                                    {
                                        strSenChar += sensitiveAttr.SensitiveReChar;
                                    }
                                    item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);
                                }
                            }

                        }
                    }
                    else if(resVal.GetType().IsClass)
                    {
                        var customProper = resVal.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
                        foreach (var item in customProper)
                        {
                            var itemValue = item.GetValue(resVal, null);
                            if (null != itemValue)
                            {
                                var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                                var sensitiveAttr = (attrName as SensitiveAttribute);
                                string strSenChar = sensitiveAttr.SensitiveReChar;
                                for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                                {
                                    strSenChar += sensitiveAttr.SensitiveReChar;
                                }
                                item.SetValue(resVal, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);
                            }
                        }
                    }

                    //var customProper3 = s.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
                    //var customProper2 = objectContent.Value.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
                    //var customProper = res.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
                    //if (!customProper.Any())
                    //{
                    //    return ;
                    //}
                    //SensitiveAttribute sensitive = new SensitiveAttribute();
                    
                    //foreach (var item in customProper)
                    //{
                    //    var itemValue = item.GetValue(res, null);
                    //    if (null != itemValue)
                    //    {
                    //        var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                    //        var sensitiveAttr = (attrName as SensitiveAttribute);
                    //        string strSenChar = sensitiveAttr.SensitiveReChar;
                    //        for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                    //        {
                    //            strSenChar += sensitiveAttr.SensitiveReChar;
                    //        }
                    //        item.SetValue(res, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);
                    //    }

                    //}


                }
            }

            base.OnActionExecuted(actionExecutedContext);   
        }
    }
View Code

 

        /// <summary>
        /// 数据脱敏
        /// </summary>
        /// <param name="resVal"></param>
        private void GetCustom(object resVal)
        {
            if (null == resVal)
            {
                return;
            }
            if (resVal.GetType().IsGenericType)
            {
                foreach (var sou in (IEnumerable)resVal)
                {
                    var customProper = sou.GetType().GetProperties().Where(p => p.CanWrite && p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
                    if (!customProper.Any())
                    {
                        break;
                    }
                    foreach (var item in customProper)
                    {
                        if (item.PropertyType == typeof(String) || item.PropertyType == typeof(Int32) || item.PropertyType == typeof(Decimal))
                        {
                            var itemValue = item.GetValue(sou, null);
                            if (null != itemValue)
                            {
                                var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                                var sensitiveAttr = (attrName as SensitiveAttribute);
                                string strSenChar = sensitiveAttr.SensitiveReChar;
                                for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                                {
                                    strSenChar += sensitiveAttr.SensitiveReChar;
                                }
                                itemValue = itemValue.ToString().Substring(0, sensitiveAttr.Start) + strSenChar + itemValue.ToString().Substring(sensitiveAttr.Start + sensitiveAttr.Len);
                                item.SetValue(sou, itemValue, null);
                            }
                        }
                        else
                        {
                            GetCustom(item);
                        }
                    }

                }
            }
            else if (resVal.GetType().IsClass)
            {
                var customProper = resVal.GetType().GetProperties().ToList().Where(p => p.CanWrite && p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());
                foreach (var item in customProper)
                {
                    var itProp = item.PropertyType.GetProperties().ToList().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());

                    if (item.PropertyType == typeof(String)|| item.PropertyType == typeof(Int32) || item.PropertyType == typeof(Decimal))
                    {
                        var itemValue = item.GetValue(resVal, null);
                        if (null != itemValue)
                        {
                            var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);
                            var sensitiveAttr = (attrName as SensitiveAttribute);
                            string strSenChar = sensitiveAttr.SensitiveReChar;
                            for (int i = 0; i < sensitiveAttr.Len - 1; i++)
                            {
                                strSenChar += sensitiveAttr.SensitiveReChar;
                            }
                            itemValue = itemValue.ToString().Substring(0, sensitiveAttr.Start) + strSenChar + itemValue.ToString().Substring(sensitiveAttr.Start + sensitiveAttr.Len);
                            item.SetValue(resVal, itemValue.ToString(), null);
                        }
                    }
                    else if (item.PropertyType.IsGenericType ||(item.PropertyType.IsClass && 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[叩响C#之门]第2章 变量 2.1 整型变量(一)发布时间:2022-07-14
下一篇:
C# base64 加密解密发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap