ASP.NET Core DisplayAttribute Localization

前端 未结 5 1008
挽巷
挽巷 2020-12-20 14:08

According to the documentation:

The runtime doesn’t look up localized strings for non-validation attributes. In the code above, “Email” (from [Display

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 14:35

    Having a Central location for all your localization whether in view or dataannotations is the best approach I can think of, and this how I got to work. In Startup.cs file after you installed nuget packages for localization add the following code

    services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization(options => 
        options.DataAnnotationLocalizerProvider = (type, factory) => new StringLocalizer(factory));
    
    services.Configure(options => {
       var cultures = new[]
       {
           new CultureInfo("en"),
           new CultureInfo("ar")
       };
       options.DefaultRequestCulture = new RequestCulture("en", "en");
       options.SupportedCultures = cultures;
       options.SupportedUICultures = cultures;
    });
    

    This way the DataAnnotationLocalizerProvider will be from the Resources.{culture}.rex -( The Resource file must have an access modifier of No code gen)- assuming that no resources will be needed for the default language, and to be able to access the resource file since no code will be generated and empty class with the same name must be created.

    and in _ViewImports.cshtml file inject the following

    @inject IHtmlLocalizer Localizer
    

    by doing this you now have a global variable Localizer to be used in any of the views for localization purposes.

    you can find further information on Globalization and localization in ASP.NET Core

提交回复
热议问题