CloudBuilder/CloudBuilder.Security/Utility/ValidateHelper.cs
owenchen 1c0c83af5f ow
2026-05-12 10:09:31 +08:00

51 lines
2.0 KiB
C#

using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.Service;
using CloudBuilder.Security.Entity;
namespace CloudBuilder.Security.Utility
{
public class ValidateHelper
{
public static void Validate(IApplicationService service, dynamic data, string tableName)
{
List<SysTableSchemaViewEntity> sysTableSchemas = service.GetRepository<IRepository<SysTableSchemaViewEntity>>().DetachedEntities.Where(x => x.TableName == tableName).ToList();
ValidateHelper.ValidateString(data, sysTableSchemas.ToArray());
}
public static void ValidateString(dynamic dynamic, SysTableSchemaViewEntity[] sysTableSchemas)
{
// 获取所有实体有效属性
var props = dynamic.GetType().GetProperties();
// 获取实体当前(现在)的值
SysTableSchemaViewEntity sysTableSchema;
int maxLength = 0;
string desName = null;
// 遍历所有属性
foreach (var prop in props)
{
// 获取属性名
var propName = prop.Name;
sysTableSchema = sysTableSchemas.Where(x => x.FieldName.Replace("_", "").ToLower() == propName.ToLower()).FirstOrDefault();
if (sysTableSchema == null) continue;
if (sysTableSchema.TypeOfName != "string") continue;
if (string.IsNullOrEmpty(prop.GetValue(dynamic, null))) continue;
maxLength = sysTableSchema.MaxLength;
object[] objs = prop.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
desName = propName;
if (objs != null && objs.Length > 0) desName = ((System.ComponentModel.DescriptionAttribute)objs[0]).Description;
if (((string)prop.GetValue(dynamic, null)).Length > maxLength)
{
throw new ValidatedException(string.Format("{0}长度不能超过【{1}】字符.", desName, maxLength));
}
}
}
}
}