您好我正在尝试为我的注册页面创建一致的验证。这是我遇到问题的财产:
[DateTimeValidation(ErrorMessageResourceType = typeof(EnValidationResources), ErrorMessageResourceName = "__LK_UserModel_BirthDate_Is_Required__")]
public DateTime BirthDate { get; set; }
在测试时,我意识到即使我为DateTime添加了自己的验证属性:
public class DateTimeValidation: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var dateTimeString = value.ToString();
DateTime dateTimeParseResult;
DateTime.TryParse(dateTimeString, out dateTimeParseResult);
if (dateTimeParseResult.Equals(default(DateTime)))
{
return new ValidationResult(ErrorMessageString);
}
return null;
}
}
如果用户发布了null DateTime,我仍然会收到此响应文本:
“无法将null值转换为System.DateTime。路径'birthDate',行 1,位置17。“
如何让asp.net web.api停止返回内置的错误响应文本?
答案 0 :(得分:0)
尝试:
[DateTimeValidation(ErrorMessageResourceType = typeof(EnValidationResources), ErrorMessageResourceName = "__LK_UserModel_BirthDate_Is_Required__")]
public DateTime? BirthDate { get; set; } //use nullable type.