自定义属性

    /// <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();

C# 自定义属性Attribute的更多相关文章

  1. Ahjesus获取自定义属性Attribute或属性的名称

    1:设置自己的自定义属性 public class NameAttribute:Attribute { private string _description; public NameAttribut ...

  2. 自定义属性Attribute的运用

    有时候需要一个枚举类,能够承载更多的信息,于是可以利用attribute这个特性. 首先编写自己业务需求类 [AttributeUsage(AttributeTargets.Field)] publi ...

  3. JS DOM属性,包括固有属性和自定义属性,以及属性获取、移除和设置

    属性分为固有属性property和自定义属性attribute 固有属性查看 固有属性可以通过ele.property 来获取,自定义属性不行 <!DOCTYPE html> <ht ...

  4. C# VS JAVA 差异 (未完待续)

    1. 静态构造函数 C#中有静态构造函数, Java中没有静态构造函数.其实Java中有一个类似静态构造函数的东东,称作静态初始化,或者静态代码块,可以通过这样的代码实现相同的功能: 但是Java中静 ...

  5. 【学】SoapExtension 学习

    http://msdn.microsoft.com/zh-cn/library/System.Web.Services.Protocols.SoapExtension_methods(v=vs.80) ...

  6. 序列化和反序列化的几种方式(JavaScriptSerializer 、XmlSerializer、DataContractSerializer)(一)

    JavaScriptSerializer 类 为启用 AJAX 的应用程序提供序列化和反序列化功能. 命名空间:   System.Web.Script.Serialization 程序集:  Sys ...

  7. Servlet概念框架

    以 Servlet 3.0 源代码为基础.Servlet 是 Javaweb 应用的基础框架,犹如孙子兵法之于作战指挥官,不可不知. 概念框架 机制: 事件 Event, 监听器 Listener 数 ...

  8. jQuery从入门到忘记

    jQuery 是一套Javascript脚本库,注意 jQuery 是脚本库,而不是脚本框架."库"不等于"框架".jQuery 并不能帮助我们解决脚本的引用管 ...

  9. jQuery 基础语法

    jQuery介绍 1.jQuery是一个轻量级的.兼容多浏览器的JavaScript库. 2.jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方便地进行Aja ...

随机推荐

  1. 神经网络中的感受野(Receptive Field)

    在机器视觉领域的深度神经网络中有一个概念叫做感受野,用来表示网络内部的不同位置的神经元对原图像的感受范围的大小.神经元之所以无法对原始图像的所有信息进行感知,是因为在这些网络结构中普遍使用卷积层和po ...

  2. Plugin execution not covered by lifecycle configuration: aspectj-maven-plugin:1.8

    现象: eclipse导入existing maven project,(父项目包含很多子项目),子项目的pom.xml报错: Plugin execution not covered by life ...

  3. 多线程《五》GIL全局解释器锁

    一 引子 定义: In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native t ...

  4. PHP的Composer 与 Packagist,简单入门

    [转]http://www.php.cn/manual/view/34000.html Composer 是一个 杰出 的依赖管理器.在 composer.json 文件中列出你项目所需的依赖包,加上 ...

  5. utp

    接口测试大致分为两种:数据驱动和代码驱动 数据驱动:主要处理用例之间没有关联关系的用例集合,一般以(excel.yaml)文件形式存储用例 代码驱动:主要是处理用例之间存在关联关系的用例(如:抽奖,需 ...

  6. 【BlockingQueue】BlockingQueue 阻塞队列实现

    前言: 在新增的Concurrent包中,BlockingQueue很好的解决了多线程中,如何高效安全“传输”数据的问题.通过这些高效并且线程安全的队列类,为我们快速搭建高质量的多线程程序带来极大的便 ...

  7. JDBC_事务概念_ACID特点_隔离级别_提交commit_回滚rollback

    事务的概念 一组要么同时执行成功,要么同时执行失败的SQL语句,是数据库操作的一个执行单元! 事务开始于: 连接到数据库上,并执行一条DML语句(insert,update或delete),前一个事务 ...

  8. Vue-think脚手架

    准备重构的项目,原来的后台是thinkPHP写的,刚刚摸VUE,不知道里面数据调用原理,想先安装vuethink学习一下. 结果安装半天,npm run dev的时候报错,尝试了很多方法,各种重装,看 ...

  9. scrapy 请求和响应

    scrapy Request类的一些参数意义 url: 就是需要请求,并进行下一步处理的url callback: 指定该请求返回的Response,由那个函数来处理. method: 一般不需要指定 ...

  10. WordPress 有关Https的设置

    开头卖萌求点击 https://www.yinghualuowu.com/ Http和Https的区别 就是多了s的区别(不是),简单点就是比http更安全了.23333.这里不打算说的太详细,知道前 ...