ASP.NET Core 8设置pt-BR文化后数据注解验证消息仍为英文
ASP.NET Core 8 Web API数据注解验证消息葡萄牙语本地化解决办法
1. 启用数据注解本地化支持
你之前仅配置了请求本地化,但遗漏了数据注解的本地化功能开启,这是核心问题。在Program.cs中添加控制器服务时,必须加上AddDataAnnotationsLocalization():
var builder = WebApplication.CreateBuilder(args); // 配置控制器并启用数据注解本地化 builder.Services.AddControllers() .AddDataAnnotationsLocalization(); // 关键:让框架加载内置的本地化验证消息 // 配置请求本地化选项 builder.Services.Configure<RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("pt-BR"), new CultureInfo("en-US") }; options.DefaultRequestCulture = new RequestCulture("pt-BR"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); var app = builder.Build(); // 注意:请求本地化中间件要放在UseRouting之前 app.UseRequestLocalization(); app.UseRouting(); app.UseAuthorization(); app.MapControllers(); app.Run();
2. 确保项目包含pt-BR本地化资源
ASP.NET Core 8的内置验证消息翻译已包含在框架依赖中,SDK风格的Web API项目默认会自动加载这些资源。如果你的项目做了依赖裁剪(比如发布时启用Trim模式),可以手动添加以下NuGet包确保资源存在:
<PackageReference Include="Microsoft.AspNetCore.Mvc.DataAnnotations" Version="8.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Localization" Version="8.0.0" />
3. 确认请求文化生效
验证请求是否正确传递了pt-BR文化:
- 在请求头中添加
Accept-Language: pt-BR - 或者在控制器方法中调试打印当前线程文化,确认设置成功:
// 控制器内调试代码 var currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture.Name; var currentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
4. 不要手动写死错误消息
模型类中的数据注解不要添加自定义ErrorMessage,否则会覆盖内置的本地化翻译,正确写法示例:
public class LoginRequest { [Required] [StringLength(50)] public string Usuario { get; set; } [Required] [StringLength(100)] public string Senha { get; set; } }
完成以上配置后,验证失败时会自动返回葡萄牙语的内置消息,比如"O campo Usuario é obrigatório"。
内容的提问来源于stack exchange,提问作者Max Bündchen
相关产品推荐
相关产品推荐

