How to localize standard error messages of validation attributes in ASP.NET Core

廉价感情. 提交于 2019-12-25 01:47:25

问题


How to localize standard error messages of validation attributes in ASP.NET Core (v2.2)? For Example, [Required] attribute has this error message "The xxx field is required."; [EmailAddress] has "The xxx field is not a valid e-mail address."; [Compare] has "'xxx' and 'yyy' do not match." and so on. In our project we use not English language and I want to find a way how to translate standard error messages without writing them directly in every attribute of every data-model class


回答1:


This is spelled out in the docs. You can do either:

  1. Use the ResourcePath option on the attribute.

    [Required(ResourcePath = "Resources")]
    

    Then, you'd add the localized message to Resources/Namespace.To.MyClass.[lang].resx.

  2. Use one resource file for all classes:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .AddDataAnnotationsLocalization(options => {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                    factory.Create(typeof(SharedResource));
            });
    }
    


来源:https://stackoverflow.com/questions/59284038/how-to-localize-standard-error-messages-of-validation-attributes-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!