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

.NET WebForms迁移至Identity后如何本地化注册表单错误信息?

.NET Identity 本地化错误消息解决方法(WebForms迁移场景)

1. 安装对应区域性的Identity资源包

.NET Identity的默认错误消息存储在资源文件中,需要安装波兰语资源包才能加载本地化文本。在NuGet包管理器中执行以下命令:

Install-Package Microsoft.AspNet.Identity.Core.pl

安装完成后,检查项目bin目录下是否生成pl文件夹,其中包含Microsoft.AspNet.Identity.Core.resources.dll文件,这是资源包生效的标志。

2. 确保应用全局区域性设置正确

虽然你已在web.config中配置了波兰语区域性,但WebForms应用可能需要额外的线程区域性设置来覆盖默认行为:

  • 打开Global.asax,在Application_BeginRequest方法中添加以下代码:
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var plCulture = new System.Globalization.CultureInfo("pl-PL");
        System.Threading.Thread.CurrentThread.CurrentCulture = plCulture;
        System.Threading.Thread.CurrentThread.CurrentUICulture = plCulture;
    }
    
  • 确认web.config中的globalization节点配置正确:
    <configuration>
      <system.web>
        <globalization uiCulture="pl" culture="pl-PL" />
      </system.web>
    </configuration>
    

3. 自定义错误消息(资源包未覆盖场景)

如果资源包中的文本不符合需求,或者某些消息未被本地化,可以通过自定义IdentityErrorDescriber来完全控制错误内容:

  • 创建自定义描述器类:
    public class PolishIdentityErrorDescriber : IdentityErrorDescriber
    {
        public override IdentityError DuplicateUserName(string userName)
        {
            return new IdentityError { Code = nameof(DuplicateUserName), Description = "该用户ID已被占用" };
        }
    
        public override IdentityError EmailRequired()
        {
            return new IdentityError { Code = nameof(EmailRequired), Description = "电子邮件为必填项" };
        }
    
        // 按需重写其他错误方法,比如InvalidEmail、PasswordTooShort等
    }
    
  • 在OWIN Startup类的ApplicationUserManager创建逻辑中注册这个自定义描述器:
    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // 替换默认错误描述器
        manager.ErrorDescriber = new PolishIdentityErrorDescriber();
        // 其他用户管理器配置(如密码规则、用户验证等)
        return manager;
    }
    

4. 清理重建项目

完成上述配置后,清理项目并重新生成,确保资源文件和自定义代码被正确编译部署。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:35:03