C# 如何将 DataAnnotations ErrorMessageResourceName 与自定义资源解决方案一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2347650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:40:03  来源:igfitidea点击:

How to use DataAnnotations ErrorMessageResourceName with custom Resource Solution

c#asp.net-mvcvalidationresourcesdata-annotations

提问by Mats

I'm building a MVC web application with C#. Since the site will be multilingual, I've implemented my own ResourceManager. This class is responsible for fetching the required resource strings from a database/cache depending on the currents thread culture and works fine so far.

我正在用 C# 构建一个 MVC Web 应用程序。由于该站点将支持多种语言,因此我实现了自己的 ResourceManager。这个类负责根据当前线程文化从数据库/缓存中获取所需的资源字符串,并且到目前为止工作正常。

My problem is, I'd like to use the my custom ResourceManager solution to fetch validation error messages when for example using the RequiredAttribute on a property. Can this be done?

我的问题是,我想使用我的自定义 ResourceManager 解决方案来获取验证错误消息,例如在属性上使用必需属性时。这能做到吗?

采纳答案by Darin Dimitrov

The RequiredAttributeallows to use a custom resource manager:

RequiredAttribute标签允许使用一个自定义的资源管理器

[Required(
    ErrorMessageResourceType = typeof(CustomResourceManager), 
    ErrorMessageResourceName = "ResourceKey")]
public string Username { get; set; }


UPDATE:

更新:

Another possibility is to write your custom attribute:

另一种可能性是编写您的自定义属性:

public class CustomRequiredAttribute : RequiredAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return YourCustomResourceManager.GetResource(name);
    }
}