简体   繁体   English

即使具有自定义验证属性,Asp.net Web.APi也会返回内置错误响应

[英]Asp.net Web.APi returns build in error response even with custom validation attribute

Hi I am trying to create create a consistent validation for my registration page.Here is the property I am having trouble with: 嗨,我正在尝试为注册页面创建一个一致的验证。这是我遇到麻烦的属性:

    [DateTimeValidation(ErrorMessageResourceType = typeof(EnValidationResources), ErrorMessageResourceName = "__LK_UserModel_BirthDate_Is_Required__")]
    public DateTime BirthDate { get; set; }

As I was testing I realized that even if I added my own validation attribute for DateTime : 在测试时,我意识到即使为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;
    }

}

If a user posts a null DateTime I still get back this response text: 如果用户发布的日期时间为空,我仍然会返回以下响应文本:

"Cannot convert null value to System.DateTime. Path 'birthDate', line 1, position 17." “无法将空值转换为System.DateTime。路径'birthDate',第1行,位置17。”

How can I make asp.net web.api to stop returning the built in error responses text? 如何使asp.net web.api停止返回内置的错误响应文本?

Try: 尝试:

[DateTimeValidation(ErrorMessageResourceType = typeof(EnValidationResources), ErrorMessageResourceName = "__LK_UserModel_BirthDate_Is_Required__")]
public DateTime? BirthDate { get; set; } //use nullable type.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM