【问题标题】:Localization on data annotation and error validation messages in ASP.NET CORE 3.1ASP.NET CORE 3.1 中数据注释和错误验证消息的本地化
【发布时间】:2023-03-13 18:54:01
【问题描述】:

如何在 ASP.NET CORE 3.1 中本地化数据注释和验证错误消息

[Required(ErrorMessage = "something")]
                [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
                [DataType(DataType.Password)]
                [Display(Name = "Password")]
                public string Password { get; set; }

我使用 Microsoft 文档中资源文件的标准实现

services.AddLocalization(option => option.ResourcesPath = ProjectConstants.LanguageResourcesPath);

        services.AddControllersWithViews()
                .AddViewLocalization(
                    LanguageViewLocationExpanderFormat.Suffix,
                      option => option.ResourcesPath = "Resources")
                .AddDataAnnotationsLocalization();

我的资源文件结构

|-资源
|---控制器
|---浏览量
|---型号

我正在重构身份页面,无法以两种语言显示标准错误消息。 Microsoft 文档中的这个示例对我不起作用.. [https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1#dataannotations-localization] 请有人帮助我

【问题讨论】:

  • 你的模型在哪里?确保资源文件的命名正确。可以在appsettings.Development.json中设置LogLevel为Debug,提交表单时查看日志。
  • 除了@XingZou 回答,This tutorialrepository 可以帮助更快地进行本地化。
  • 您好,命名资源时出现问题,我找到了,但问题很大。当我尝试将资源公开时出现错误“InvalidOperationException:无法检索属性 'Name',因为本地化失败。”而且我在 Visual Studio 中遇到 resxcodegenerator 错误“PublicResXFileCodeGenerator 无法为输入文件‘Resource.en-US.resx’生成输出,但没有记录特定错误。”我已经尽力了,还是无法解决,有没有人遇到过这个问题?

标签: validation asp.net-core localization resources globalization


【解决方案1】:

用于添加 DataAnnotations 本地化 InputModel 在默认标识Register 页面(位于/Areas/Identity/Pages/Account/Register.cshtml.cs)中,您需要将资源文件命名为

Areas.Identity.Pages.Account.RegisterModel+InputModel.en-US.resx

对于PageModel中的任何嵌套模型,您需要使用+而不是.

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多