You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC中ModelState错误信息本地化失效问题排查

解决ASP.NET Core MVC数据注解本地化失效问题

1. 检查资源文件配置

  • 资源文件命名必须匹配模型类:比如模型是LoginViewModel,对应本地化文件要命名为LoginViewModel.en-US.resx、LoginViewModel.zh-CN.resx,且和模型放在同一目录,或指定的Resources文件夹内。
  • 资源文件的访问修饰符要设为public(默认是internal),否则数据注解无法读取资源内容。

2. 验证本地化服务配置

确保Program.cs中正确注册本地化服务,关键代码如下:

// 若资源放在Resources文件夹,指定路径
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.AddControllersWithViews()
    .AddDataAnnotationsLocalization(options =>
    {
        // 绑定模型对应的资源类,用共享资源则替换为共享资源类型
        options.DataAnnotationLocalizerProvider = (type, factory) =>
            factory.Create(typeof(LoginViewModel));
    })
    .AddViewLocalization();

// 配置支持的文化
var supportedCultures = new[] { "en-US", "zh-CN" };
var localizationOptions = new RequestLocalizationOptions()
    .SetDefaultCulture("zh-CN")
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);

app.UseRequestLocalization(localizationOptions);

3. 数据注解的正确写法

  • 模型与资源文件同名时,可省略ResourceType:
[Display(Name = "LoginUserName")]
public string UserName { get; set; }
  • 使用共享资源文件(比如SharedResources.resx)时,必须指定ResourceType:
[Display(Name = "LoginUserName", ResourceType = typeof(SharedResources))]
public string UserName { get; set; }

4. 视图中正确渲染本地化文本

必须使用Html.DisplayNameFor或Html.LabelFor,不能直接硬编码字段名:

@model LoginViewModel
<div class="form-group">
    @Html.LabelFor(m => m.UserName)
    @Html.TextBoxFor(m => m.UserName)
</div>

5. 确认请求文化切换生效

验证当前请求的文化是否正确,可在视图中添加:

<p>当前文化:@System.Globalization.CultureInfo.CurrentUICulture.Name</p>

可通过查询字符串(?culture=en-US)、Cookie或Accept-Language请求头切换文化。

6. 清理并重新生成项目

资源文件修改后可能无法自动生效,右键项目选择清理,再重新生成,确保资源文件被正确嵌入程序集。


内容的提问来源于stack exchange,提问作者Pluto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 20:41:07