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

ASP.NET MVC应用中Identity错误消息本地化失败求助

解决ASP.NET Core Identity页面本地化问题

1. 确认资源文件结构与配置

如果你的资源文件名为ErrorMessages.resx(英文)、ErrorMessages.zh-Hans.resx(中文),需确保:

  • 文件放在项目根目录的Resources文件夹下
  • 右键资源文件→属性,将「自定义工具」设为ResXFileCodeGenerator,「自定义工具命名空间」与项目根命名空间一致(例如项目名为MyWebApp,则命名空间为MyWebApp.Resources)

2. 重写IdentityErrorDescriber绑定资源

创建自定义错误描述器,通过IStringLocalizer读取资源文件内容,覆盖Identity默认错误消息:

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Localization;

public class CustomIdentityErrorDescriber : IdentityErrorDescriber
{
    private readonly IStringLocalizer<ErrorMessages> _localizer;

    public CustomIdentityErrorDescriber(IStringLocalizer<ErrorMessages> localizer)
    {
        _localizer = localizer;
    }

    // 重写需要本地化的错误方法,示例:密码需包含数字
    public override IdentityError PasswordRequiresDigit()
    {
        return new IdentityError
        {
            Code = nameof(PasswordRequiresDigit),
            Description = _localizer["RequiredNum"]
        };
    }

    // 按需重写其他Identity错误,如密码过短、用户名重复等
    public override IdentityError PasswordTooShort(int length)
    {
        return new IdentityError
        {
            Code = nameof(PasswordTooShort),
            Description = _localizer["PasswordTooShort", length]
        };
    }
}

3. 修正Program.cs的服务注册顺序

调整服务配置顺序,确保本地化配置优先于Identity服务,并注册自定义错误描述器:

// 1. 配置本地化资源路径
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

// 2. 设置支持的文化
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("zh-Hans") };
    options.DefaultRequestCulture = new RequestCulture("en-US");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

// 3. 添加Controllers和Views的本地化支持
builder.Services.AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

// 4. 注册Identity服务并绑定自定义错误描述器
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddErrorDescriber<CustomIdentityErrorDescriber>(); // 关键步骤:替换默认错误描述器

var app = builder.Build();

// 5. 启用请求本地化,必须放在UseRouting之前
app.UseRequestLocalization();

// 后续中间件配置
app.UseRouting();
app.UseAuthorization();

app.MapRazorPages(); // Identity页面基于Razor Pages,需添加此路由映射
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

4. 在Identity PageModel中正确使用本地化

如果需要在Register.cshtml.cs等页面直接调用资源,需先注入IStringLocalizer<ErrorMessages>:

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Localization;

public class RegisterModel : PageModel
{
    private readonly IStringLocalizer<ErrorMessages> _localizer;

    public RegisterModel(IStringLocalizer<ErrorMessages> localizer)
    {
        _localizer = localizer;
    }

    // 示例:暴露本地化文本供页面调用
    public string RequiredNumTip => _localizer["RequiredNum"];

    // 其他业务逻辑...
}

在Register.cshtml中引用:

<p>@Model.RequiredNumTip</p>

常见排查点

  • 确认UseRequestLocalization的位置:必须放在UseRouting和UseAuthorization之前,否则文化设置不生效
  • 测试文化切换:通过URL参数(如?culture=zh-Hans)、Cookie或请求头切换语言,验证资源是否加载正确
  • 检查资源文件生成:确保资源文件已生成对应的C#类,可通过查看项目的obj目录确认

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:18:31