예제 #1
0
 public static void EntityCoding(object entity, bool encode)
 {
     if (entity != null)
     {
         Type           type       = entity.GetType();
         PropertyInfo[] properties = type.GetProperties();
         PropertyInfo[] array      = properties;
         for (int i = 0; i < array.Length; i++)
         {
             PropertyInfo propertyInfo = array[i];
             if (propertyInfo.GetCustomAttributes(typeof(HtmlCodingAttribute), true).Length != 0)
             {
                 if (!propertyInfo.CanWrite || !propertyInfo.CanRead)
                 {
                     throw new Exception("使用HtmlEncodeAttribute修饰的属性必须是可读可写的");
                 }
                 if (!propertyInfo.PropertyType.Equals(typeof(string)))
                 {
                     throw new Exception("非字符串类型的属性不能使用HtmlEncodeAttribute修饰");
                 }
                 string text = propertyInfo.GetValue(entity, null) as string;
                 if (!string.IsNullOrEmpty(text))
                 {
                     if (encode)
                     {
                         propertyInfo.SetValue(entity, Globals.HtmlEncode(text), null);
                     }
                     else
                     {
                         propertyInfo.SetValue(entity, Globals.HtmlDecode(text), null);
                     }
                 }
             }
         }
     }
 }