不知道怎么表達這個東西,先記錄一下吧,如果你們有好的想法可以聯系我,共同進步
/// <summary>
/// 自定義屬性幫助類
/// </summary>
public class AttributeHelper
{
/// <summary>
/// 獲取字符串字節長度
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int StringToByteLength(string str)
{
//使用Unicode編碼的方式將字符串轉換為字節數組,它將所有字符串(包括英文中文)全部以2個字節存儲
byte[] bytestr = System.Text.Encoding.UTF8.GetBytes(str);
int j = 0;
for (int i = 0; i < bytestr.GetLength(0); i++)
{
//取余2是因為字節數組中所有的雙數下標的元素都是unicode字符的第一個字節
if (i % 2 == 0)
{
j++;
}
else
{
//單數下標都是字符的第2個字節,如果一個字符第2個字節為0,則代表該Unicode字符是英文字符,否則為中文字符
if (bytestr[i] > 0)
{
j++;
}
}
}
return j;
}
/// <summary>
/// 驗證字段屬性
/// </summary>
public void Validate()
{
ValidationContext context = new ValidationContext(this, serviceProvider: null, items: null);
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(this, context, results, true);
if (isValid == false)
{
StringBuilder sbrErrors = new StringBuilder();
foreach (var validationResult in results)
{
sbrErrors.AppendLine(validationResult.ErrorMessage);
}
throw new ValidationException(sbrErrors.ToString());
}
}
/// <summary>
/// 判斷字符串字節長度
/// </summary>
public class IsByteLength : ValidationAttribute
{
public IsByteLength(string errorMsg, int len)
{
this.ErrorMsg = errorMsg;
this.Len = len;
}
public string ErrorMsg { get; private set; }
public int Len { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value.GetType().Equals(typeof(string)))
{
if (StringToByteLength(value.ToString()) > Len)
{
var error = new ValidationResult(ErrorMsg);
return error;
}
}
return null;
}
}
public static string ObjToString( object thisValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return "";
}
public class IsFieldVereist : ValidationAttribute
{
public string ErrorMsg { get; private set; }
public string TypeName { get; private set; }
public IsFieldVereist(string errorMsg, string typeName="")
{
this.ErrorMsg = errorMsg;
this.TypeName = typeName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!string.IsNullOrWhiteSpace(TypeName))
{
var tempData = Convert.ChangeType(validationContext.ObjectInstance, validationContext.ObjectType);
System.Reflection.PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(TypeName);
if (value != null || !string.IsNullOrWhiteSpace(ObjToString(value)))
{
if (propertyInfo.GetValue(tempData, null) == null)
{
var error = new ValidationResult(ErrorMsg);
return error;
}
}
}
else
{
if (value == null || string.IsNullOrWhiteSpace(ObjToString(value)))
{
var error = new ValidationResult(ErrorMsg);
return error;
}
}
return null;
}
}
}
