【问题标题】:Localizing DataAnnotations of scaffolded Identity models本地化脚手架身份模型的 DataAnnotations
【发布时间】:2021-02-12 10:18:35
【问题描述】:

ASP.NET core 5.0 mvc 项目,我想本地化 scaffolded Identity 页面。

视图本地化有效(在脚手架剃须刀文件中使用 IViewLocalizer),但使用共享资源文件时 dataAnnotations 本地化失败。

按照MS docs 我有:

DataAnnotationLocalizerProvider 设置在Startup.cs

services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization(options => {
        options.DataAnnotationLocalizerProvider = (type, factory) =>
            factory.Create(typeof(MyApp.SharedResources));
});

我的文化在Startup.cs中配置和设置

public void ConfigureServices(IServiceCollection services) {
    ...
    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("fr")
        };

        options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
    });
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(locOptions.Value);
    ...
}

Resources 文件夹与

  • 我的应用命名空间中的空类 SharedResources.cs
  • 关联的资源文件SharedResources.fr.resx

我的脚手架身份页面,即Login.cshtml.cs,带有dataAnnotations:

    public class InputModel
    {
        [Required(ErrorMessage = "The Email field is required.")]
        [EmailAddress(ErrorMessage = "The Email field is not a valid email address.")]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required(ErrorMessage = "The Password field is required.")]
        [Display(Name = "Password")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

尽管如此,我的标签和错误消息仍未翻译。

我错过了什么?脚手架文件有什么限制吗?

【问题讨论】:

    标签: asp.net-identity data-annotations asp.net-core-5.0 asp.net-core-localization


    【解决方案1】:

    好的,感谢Ryan answer,我可以让它与以+ 命名的专用resx 文件一起使用,因为身份模型具有嵌套类。

    这里记录的是脚手架 mvc Login 模型的文件名:

    Areas.Identity.Pages.Account.LoginModel+InputModel.fr.resx
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2023-01-04
      • 2020-04-12
      • 2021-10-02
      • 2020-11-23
      相关资源
      最近更新 更多