using Appointment.Entity.Utility;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Appointment.Entity.ValidateAttribute
{
///
/// 验证的执行
///
///
/// Add:yuangb 2019-3-5
///
public static class AttributeExtend
{
///
/// 全部实体属性根据特性校验
///
///
/// 验证的实体
///
public static ApiResult Validate(this T t) where T : class
{
List validates = new List();
Type type = t.GetType();
foreach (PropertyInfo prop in type.GetProperties())
{
object oValue = prop.GetValue(t);
foreach (ValidateAttribute attr in prop.GetCustomAttributes(typeof(ValidateAttribute), true))
{
string msg = attr.Validate(oValue);
if (!string.IsNullOrWhiteSpace(msg)) validates.Add(msg);
}
// 2020-10-12 添加屏蔽HTML注入
if (prop.PropertyType.Name == "String")
{
string sValue = (string)prop.GetValue(t);
if (sValue != null && !string.IsNullOrEmpty(sValue))
{
var isIgnoreHtml = prop.GetCustomAttribute(typeof(IsIgnoreHtml), true);
if (isIgnoreHtml == null)
{
sValue = sValue.Replace("<", "<").Replace(">", ">");
prop.SetValue(t, sValue);
}
}
}
}
return validates.Count == 0 ? ApiResult.Success() : ApiResult.Failed(string.Join(",", validates));
}
///
/// 指定实体的属性名称,根据特性进行校验
///
///
/// 验证的实体
/// 实体的属性名称
///
public static ApiResult Validate(this T t, List list) where T : class
{
List validates = new List();
Type type = t.GetType();
foreach (PropertyInfo prop in type.GetProperties())
{
object oValue = prop.GetValue(t);
if (list.Contains(prop.Name))
{
foreach (ValidateAttribute attr in prop.GetCustomAttributes(typeof(ValidateAttribute), true))
{
string msg = attr.Validate(oValue);
if (!string.IsNullOrWhiteSpace(msg)) validates.Add(msg);
}
}
}
return validates.Count == 0 ? ApiResult.Success() : ApiResult.Failed(string.Join(",", validates));
}
///
/// 使用委托,全部实体属性根据特性校验
///
///
/// 验证的实体
/// 一个ApiResult入参,一个ApiResult返回值的委托
///
public static ApiResult Validate(this T t, Func func)
{
List validates = new List();
Type type = t.GetType();
foreach (PropertyInfo prop in type.GetProperties())
{
object oValue = prop.GetValue(t);
foreach (ValidateAttribute attr in prop.GetCustomAttributes(typeof(ValidateAttribute), true))
{
string msg = attr.Validate(oValue);
if (!string.IsNullOrWhiteSpace(msg))
{
validates.Add(msg);
}
}
}
return validates.Count == 0 ? func.Invoke(ApiResult.Success()) : ApiResult.Failed(string.Join(",", validates));
}
}
}