自定义属性

    /// <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 = ;
this.Len = ;
this.SensitiveReChar = "*";
} public SensitiveAttribute(SensitiveType type = SensitiveType.IdNumber,int start = ,int len = ,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
}

类:

    /// <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 = )]
public string IdCard { get; set; }
}

获取属性

    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() == )
{
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 = ; i < sensitiveAttr.Len - ; 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; }
}
    /// <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 = ; i < sensitiveAttr.Len - ; 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 = ; i < sensitiveAttr.Len - ; 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 = ;
private static string SYMBOL = "*"; public static String toConceal(String value)
{
if (null == value || "".Equals(value))
{
return value;
}
int len = value.Length;
int pamaone = len / ;
int pamatwo = pamaone - ;
int pamathree = len % ;
StringBuilder stringBuilder = new StringBuilder();
if (len <= )
{
if (pamathree == )
{
return SYMBOL;
}
stringBuilder.Append(SYMBOL);
stringBuilder.Append(value.Substring(len - ,));
}
else
{
if (pamatwo <= )
{
stringBuilder.Append(value.Substring(, ));
stringBuilder.Append(SYMBOL);
stringBuilder.Append(value.Substring(len - , )); }
else if (pamatwo >= SIZE / && SIZE + != len)
{
int pamafive = (len - SIZE) / ;
stringBuilder.Append(value.Substring(, pamafive));
for (int i = ; i < SIZE; i++)
{
stringBuilder.Append(SYMBOL);
}
if ((pamathree == && SIZE / == ) || (pamathree != && SIZE % != ))
{
stringBuilder.Append(value.Substring(len - pamafive));
}
else
{
stringBuilder.Append(value.Substring(len - (pamafive + )));
}
}
else
{
int pamafour = len - ;
stringBuilder.Append(value.Substring(, ));
for (int i = ; i < pamafour; i++)
{
stringBuilder.Append(SYMBOL);
}
stringBuilder.Append(value.Substring(len - ));
}
}
return stringBuilder.ToString(); } }

自定义过滤器:

    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 = ; i < sensitiveAttr.Len - ; 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 = ; i < sensitiveAttr.Len - ; 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);
}
}
        /// <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 = ; i < sensitiveAttr.Len - ; i++)
{
strSenChar += sensitiveAttr.SensitiveReChar;
}
itemValue = itemValue.ToString().Substring(, 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 = ; i < sensitiveAttr.Len - ; i++)
{
strSenChar += sensitiveAttr.SensitiveReChar;
}
itemValue = itemValue.ToString().Substring(, sensitiveAttr.Start) + strSenChar + itemValue.ToString().Substring(sensitiveAttr.Start + sensitiveAttr.Len);
item.SetValue(resVal, itemValue.ToString(), null);
}
}
else if (item.PropertyType.IsGenericType ||(item.PropertyType.IsClass && itProp.Any()))
{
GetCustom(item.GetValue(resVal, null));
} }
}
}

获取属性

方法一、定义一个类的对象获取

Person p = new Person();
foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties())
{
Console.WriteLine(info.Name);
}

方法二、通过类获取

Person p = new Person();
foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties())
{
Console.WriteLine(info.Name);
}

3、通过属性名获取属性值

p.Name = "张三";
var name = p.GetType().GetProperty("Name").GetValue(p, null);
Console.WriteLine(name);

4、完整代码及结果显示

var properties = typeof(Person).GetProperties();
foreach (System.Reflection.PropertyInfo info in properties)
{
Console.WriteLine(info.Name);
} Console.WriteLine("另一种遍历属性的方法:"); Person p = new Person();
foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties())
{
Console.WriteLine(info.Name);
} Console.WriteLine("通过属性值获取属性:"); p.Name = "张三";
var name = p.GetType().GetProperty("Name").GetValue(p, null);
Console.WriteLine(name);
Console.ReadLine();

最新文章

  1. .数据库连接池技术:DBCP和C3P0
  2. [转] How to debug a ARM Cortex-M hard fault exception
  3. MFC 网络编程中::connect返回-1问题
  4. hyper-v虚拟化管理
  5. 转:js清空数组
  6. 【转】解决jsp参数传递乱码的问题
  7. mysql 日期类型比较
  8. HDU 4310 Hero (贪心算法)
  9. Failed to load JavaHL Library解决方法
  10. JavaSE复习日记 : 抽象类
  11. xpath的文本获取
  12. [UWP小白日记-8]一些零碎的东西
  13. git基本语法
  14. android EventBus 3.0使用指南
  15. 粒子系统属性Life,发射速率和总数的关系
  16. String StringBuffer StringBulider 详细看https://www.cnblogs.com/su-feng
  17. Linux 内核里的数据结构:红黑树(rb-tree)
  18. [CQOI2017]小Q的棋盘
  19. 【java】浅谈swtich
  20. 【372】Kaggle 相关经验

热门文章

  1. iOS APP打包上传到APPstore的最新步骤
  2. 第五篇 Python内置函数
  3. 后置处理器----JSON提取器
  4. 【转】如何把CD上的音乐拷贝到电脑上
  5. 51nod1228 序列求和(伯努利数)
  6. 八大排序算法的python实现(三)冒泡排序
  7. Idea中文输入问题2
  8. 【重要的css属性学习】看了乙醇的文章,统计了几个高star前端框架下,Css属性出现最多的,这里学习记录一下
  9. JS 为任意元素添加任意事件的兼容代码
  10. asp web服务