企业库6 WCF验证:自定义验证器错误消息

时间:2015-04-16 07:17:21

标签: c# wcf validation enterprise-library

我在WCF中使用Enterprise Library 6 Validation。我做了一个自定义验证器。当我使用它时,我指定MessageTemplate。发生错误时,不会显示MessageTemplate,而是显示自定义验证程序的DoValidate中给出的消息。

自定义验证器

public sealed class EmailValidatorAttribute : ValidatorAttribute
{
    protected override Validator DoCreateValidator(Type targetType)
    {
        return new EmailValidator();
    }
}

public sealed class EmailValidator : Validator
{
    public EmailValidator()
        : base("Email Validation", "String")
    {
    }
    protected override string DefaultMessageTemplate
    {
        get { return "Email Validation"; }
    }
    // This method does the actual validation
    public override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
    {
        Regex emailRegex = new Regex(IConnect.DataContract.WCFServiceResources.EmailRegex);
        Match match = emailRegex.Match((string)objectToValidate);
        if (!match.Success)
        {
            LogValidationResult(validationResults, "Invalid Email Address.", currentTarget, key);
        }
    }
}

WCF

[OperationContract]
[FaultContract(typeof(ValidationFault))]
string EmailAddressCheck([EmailValidator(MessageTemplate = "Enter a Valid Email ID.")]string email);
  

目前正在显示“无效的电子邮件地址。”   自定义验证码的 DoValidate

但是

  

我想在WCF代码中 MessageTemplate 中显示“输入有效的电子邮件ID。”

怎么做?

1 个答案:

答案 0 :(得分:1)

最后我找到了回答我的问题。

public override void DoValidate(
    object objectToValidate,
    object currentTarget,
    string key,
    ValidationResults validationResults)
{
    Regex emailRegex = new Regex(IConnect.DataContract.WCFServiceResources.EmailRegex);
    Match match = emailRegex.Match((string)objectToValidate);
    if (!match.Success)
    {
        LogValidationResult(
           validationResults,
           // The next line does the trick
           string.Format(this.MessageTemplate, new object[] { objectToValidate }),
           currentTarget,
           key);
    }
}

LogValidationResult中实现这一诀窍的部分是:

string.Format(this.MessageTemplate, new object[] { objectToValidate })