C# 正则表达式属性构造函数调用一次

发布于 2024-09-10 14:30:52 字数 573 浏览 9 评论 0原文

我正在使用数据注释来验证电子邮件地址。

为了在电子邮件地址无效时显示错误消息,我使用了名为 ErrorMessages 的 RESX 文件。

我的代码是这样的:

public class EmailAdressAttribute : RegularExpressionAttribute
{
    public EmailAdressAttribute()
        : base(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,3}|[0-9]{1,4})(\]?)$")
    {

        ErrorMessage = ErrorMessages.ValidateEmailAdress;
    }

当我在运行应用程序时更改为我的 ASP.NET MVC 应用程序的语言(当前文化)时,仍然显示旧语言。
经过调试我发现这个属性的构造函数只被调用一次(当我第一次使用它时)。

属性是如何被缓存的? 如何从资源文件中显示正确的错误消息?

I am using data annotations to validate an emailaddress.

To show an error message when the emailaddress is not valid, I use a RESX file called ErrorMessages.

My code is like this:

public class EmailAdressAttribute : RegularExpressionAttribute
{
    public EmailAdressAttribute()
        : base(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,3}|[0-9]{1,4})(\]?)$")
    {

        ErrorMessage = ErrorMessages.ValidateEmailAdress;
    }

When I change to language (current culture) of my asp.net mvc application while running the application, the old language is still shown.
After debugging I found out that the constructor for this attribute is only called once(when I use it for the first time ).

How is the attribute being cached ?
How can I show the correct error message from the resource file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光①夏 2024-09-17 14:30:52

与其在构造函​​数中设置 ErrorMessage 属性的值,不如重写该属性并在需要时从资源中读取该文本怎么样?

public override string ErrorMessage
{
   get { return ErrorMessages.ValidateEmailAdress; }
}

该属性不是属于类的实例,而是属于类型。这就是为什么它在应用程序的生命周期中只构建一次。

Instead of setting the value of your ErrorMessage property in the constructor, how about overriding that property and reading that text from the resource at the moment it's needed?

public override string ErrorMessage
{
   get { return ErrorMessages.ValidateEmailAdress; }
}

The attribute is not something that belongs to an instance of the class, but to the Type. That's why it is constructed only once in your app's lifetime.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文