.NET Core 6中如何本地化非DataAnnotation类错误消息?
解决.NET Core 6中Identity密码不匹配消息的本地化问题
你遇到的核心问题是:"Incorrect password."这条错误属于ASP.NET Core Identity的内置错误,而非DataAnnotations验证消息,所以之前针对DataAnnotations的本地化配置无法覆盖它。.NET Framework里的默认资源DLL在.NET Core中被移除,需要手动配置Identity的本地化资源。
解决步骤如下:
1. 创建匹配Identity命名空间的本地化资源文件
- 在项目中新建路径
Resources/Microsoft.AspNetCore.Identity(不存在则手动创建) - 在该路径下添加资源文件
IdentityResources.es.resx - 打开resx文件,添加键值对:
- 键:
PasswordMismatch - 值:
Contraseña incorrecta.(或你需要的西班牙语消息)
- 键:
- 确保该资源文件的生成操作设为「嵌入的资源」,自定义工具设为「ResXFileCodeGenerator」(Visual Studio环境下)
2. 自定义Identity错误描述器读取本地化消息
创建继承自IdentityErrorDescriber的类,通过IStringLocalizer读取资源文件内容:
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Localization; public class LocalizedIdentityErrorDescriber : IdentityErrorDescriber { private readonly IStringLocalizer<IdentityResources> _localizer; public LocalizedIdentityErrorDescriber(IStringLocalizer<IdentityResources> localizer) { _localizer = localizer; } public override IdentityError PasswordMismatch() { return new IdentityError { Code = nameof(PasswordMismatch), Description = _localizer[nameof(PasswordMismatch)] }; } // 如需本地化其他Identity错误,可在此重写对应方法,比如InvalidPassword、DuplicateEmail等 }
3. 在Program.cs中注册自定义错误描述器
在现有Identity注册代码后,添加以下配置:
// 替换为你项目实际的Identity注册代码,比如AddDefaultIdentity或AddIdentity builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>() .AddErrorDescriber<LocalizedIdentityErrorDescriber>(); // 新增这行 // 保留你已有的本地化配置 builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); builder.Services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("es") }; options.DefaultRequestCulture = new RequestCulture("es"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); app.UseRequestLocalization();
4. 验证配置
启动项目后,用错误的旧密码尝试修改操作,此时错误集合应返回你设置的西班牙语消息。
如果仍未生效,检查以下几点:
- 资源文件的命名和路径是否完全匹配
Microsoft.AspNetCore.Identity.IdentityResources - 请求文化是否正确设置(可通过请求头
Accept-Language指定es,或依赖默认配置的es) - 自定义错误描述器是否被正确注入DI容器
内容的提问来源于stack exchange,提问作者jstuardo
相关产品推荐
相关产品推荐

