如何将C# .NET、Entity Framework及Identity的消息转换为其他语言文化?
将Entity Framework与.NET Identity默认消息本地化(以西班牙语为例)
1. 配置应用本地化服务
在Program.cs中添加本地化配置,指定支持的文化(比如西班牙语es-ES)并启用中间件:
// 添加本地化服务,指定资源文件路径 builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); // 配置请求本地化选项 builder.Services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("es-ES") }; options.DefaultRequestCulture = new RequestCulture("es-ES"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); // 启用请求本地化中间件(需放在路由中间件之前) app.UseRequestLocalization();
2. 添加.NET Identity本地化资源文件
.NET Identity的错误消息有固定键值,只需创建对应语言的资源文件覆盖默认内容:
- 新建
Resources文件夹 - 在文件夹内创建
Microsoft.AspNetCore.Identity.IdentityResources.es.resx(西班牙语资源文件) - 打开resx文件,添加需要本地化的键值对,示例:
键名 西班牙语值 DuplicateUserName El nombre de usuario '{0}' ya está en uso.PasswordTooShort La contraseña debe tener al menos {0} caracteres.InvalidEmail La dirección de correo electrónico no es válida.
3. 让Identity使用本地化资源
注册Identity服务时,确保它能读取本地化资源:
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>() .AddLocalization(options => options.ResourcesPath = "Resources");
如果需要更灵活的自定义逻辑,可以创建继承自IdentityErrorDescriber的类,注入字符串本地化器返回自定义消息:
public class SpanishIdentityErrorDescriber : IdentityErrorDescriber { private readonly IStringLocalizer<SpanishIdentityErrorDescriber> _localizer; public SpanishIdentityErrorDescriber(IStringLocalizer<SpanishIdentityErrorDescriber> localizer) { _localizer = localizer; } public override IdentityError DuplicateUserName(string userName) { return new IdentityError { Code = nameof(DuplicateUserName), Description = _localizer["DuplicateUserName", userName] }; } // 按需重写其他错误方法,比如PasswordTooShort、InvalidEmail等 }
然后注册这个自定义描述器:
builder.Services.AddScoped<IdentityErrorDescriber, SpanishIdentityErrorDescriber>();
4. Entity Framework验证消息本地化
EF Core的数据注解验证消息(比如必填、长度限制)也可通过资源文件本地化:
- 在
Resources文件夹创建DataAnnotations.es.resx - 添加对应键值对,示例:
键名 西班牙语值 RequiredAttribute_ValidationError El campo {0} es obligatorio.StringLengthAttribute_ValidationError El campo {0} debe tener entre {2} y {1} caracteres.
随后在Program.cs配置数据注解本地化:
builder.Services.AddControllersWithViews() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(DataAnnotations)); });
验证效果
完成配置后,当用户注册时若用户名已存在,系统会返回西班牙语提示:El nombre de usuario 'test@gmail.com' ya está en uso.
内容的提问来源于stack exchange,提问作者ViniciusDevelopment
相关产品推荐
相关产品推荐

