排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256
50010702506256
欢迎加群交流技术
分类:
.net
前言
衔接上一篇文章,在配置好加解密之后,我从配置文件直接映射的实体到代码里,里面的属性含有加密数据,也可能传递一个List。我需要对传递过来的对象属性进行解密并返回。
下边来上代码
解密实体中所有属性,并重新赋值
/// <summary>
/// 遍历对象属性,尝试进行解密,失败则原样返回
/// </summary>
/// <typeparam name="T">List或者实体</typeparam>
/// <param name="model"></param>
/// <returns></returns>
public static T ForeachClassProperties<T>(T model) where T : class, new()
{
try
{
string privateKey = RSAHelper.GetPrivateKey();
Type t = model.GetType();
PropertyInfo[] propertyList = t.GetProperties();
//除开list
if (t.Name.IndexOf("List`", StringComparison.Ordinal) < 0)
{
foreach (PropertyInfo item in propertyList)
{
if (item.PropertyType.Name == "String")
{
if (item.CanWrite == true && item.PropertyType == typeof(string))
{
var value = item.GetValue(model) ?? "";
if (value.IsNullOrEmpty())
{
continue;
}
try
{
item.SetValue(model, RSAHelper.Decrypt(privateKey, value.ToString()));
}
catch (Exception e)
{
continue;
}
}
}
}
}
else
{
//获取
var instanceName = propertyList[2].PropertyType.Name;
var namespaceName = propertyList[2].PropertyType.Namespace;
Assembly assembly = propertyList[2].PropertyType.Assembly;
//Assembly.Load($"{namespaceName.Split('.')[0]}.{namespaceName.Split('.')[1]}");//加载程序集
Type type = propertyList[2].PropertyType;
//assembly.GetType(namespaceName + "." + instanceName);
Type listType = typeof(List<>);
//指定泛型的具体类型
Type newType = listType.MakeGenericType(new Type[] { type });
dynamic list = Activator.CreateInstance(newType, model);
foreach (var item in list)
{
propertyList = item.GetType().GetProperties();
foreach (PropertyInfo item1 in propertyList)
{
if (item1.CanWrite == true && item1.PropertyType == typeof(string))
{
object value = item1.GetValue(item) ?? "";
if (value.IsNullOrEmpty())
{
continue;
}
try
{
item1.SetValue(item, RSAHelper.Decrypt(privateKey, value.ToString()));
}
catch (Exception e)
{
continue;
}
}
}
}
model = list;
}
return model;
}
catch (Exception e)
{
return model;
}
}评价