RegularExpressionAttribute
我们为我们的 MVC3 应用程序编写了一个自定义。定制的目的RegularExpressionAttribute
是,我们想用关键字替换资源文件消息中的标记。例如“字段 __ 有一些无效字符”。
所以我们想用关键字替换_
token 。Address
ResourceManager(_resourceManagerType.FullName,
System.Reflection.Assembly.Load(AssemblyNames.TRUETRAC_RESOURCES)).GetString(_errorMessageResourceName).Replace("_","Address");
自定义属性如下,
public class CustomRegularExpressionAttribute : RegularExpressionAttribute
{
string _errorMessageResourceName;
Type _resourceManagerType;
public CustomRegularExpressionAttribute(string _pattern, string fieldName, string errorMessageResourceName, Type resourceManagerType)
: base(_pattern)
{
_errorMessageResourceName = errorMessageResourceName;
_resourceManagerType = resourceManagerType;
this.ErrorMessage = FormatErrorMessage(fieldName);
}
public override string FormatErrorMessage(string fieldName)
{
return //Resources.en_MessageResource.ResourceManager.GetString(fieldName);
new ResourceManager(_resourceManagerType.FullName, System.Reflection.Assembly.Load(AssemblyNames.TRUETRAC_RESOURCES)).GetString(_errorMessageResourceName).Replace("__", fieldName);
}
}
public class CustomRegularExpressionValidator : DataAnnotationsModelValidator<CustomRegularExpressionAttribute>
{
private readonly string _message;
private readonly string _pattern;
public CustomRegularExpressionValidator(ModelMetadata metadata, ControllerContext context, CustomRegularExpressionAttribute attribute)
: base(metadata, context, attribute)
{
_pattern = attribute.Pattern;
_message = attribute.ErrorMessage;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
ErrorMessage = _message,
ValidationType = "regex"
};
rule.ValidationParameters.Add("pattern", _pattern);
return new[] { rule };
}
}
然后我们在 Global.aspx Application_Start 事件中注册这个属性。
void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
// Register CustomRegularExpressionValidator
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomRegularExpressionAttribute), typeof(CustomRegularExpressionValidator));
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
并应用于我们的模型属性,如下所示:
[CustomRegularExpression(RegularExpression.Alphanumeric, "Address", "CV_Address", typeof(Resources.en_MessageResource))]
public string Address { get; set; }
问题是我们在应用程序中实现本地化,而构造函数CustomRegularExpressionAttribute
只调用一次。就像如果应用程序的启动文化是英语,然后我们将应用程序的文化更改为西班牙语,但消息CustomRegularExpressionAttribute
仍然显示为英文,因为构造函数CustomRegularExpressionAttribute
只调用了一次,并且它已被调用为英文消息。
任何人都可以告诉为什么是这个问题?为什么构造函数CustomRegularExpressionAttribute
不调用每个请求?