我正在WCF中使用Enterprise 6验证。我已经做了一个定制的Validator。当我使用它时,我指定了一个MessageTemplate。当发生错误时,它不是显示MessageTemplate,而是显示自定义验证器的DoValidate中给出的消息。
自定义Validator
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);目前,它正在显示“无效电子邮件地址”。自定义Validator代码的DoValidate中定义的。
但
我想向MessageTemplate 显示“输入有效的电子邮件ID”,是在WCF代码中定义的
如何做到这一点?
发布于 2015-04-20 06:51:01
最后我找到了我的问题的答案。
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 })https://stackoverflow.com/questions/29667873
复制相似问题