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

ASP.NET Core 3 Identity密码规则配置无效问题求助

这问题我之前也碰到过,核心原因是配置顺序不对!你先调用了services.Configure<IdentityOptions>,但后面的AddDefaultIdentity方法内部会自动设置Identity的默认规则(包括密码长度必须6位),直接把你之前的配置覆盖了。

给你两个靠谱的解决办法:

方法一:直接在AddDefaultIdentity中配置密码规则

把密码配置直接放到AddDefaultIdentity的参数lambda里,这样配置会直接覆盖默认值,不会被后续操作覆盖:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    // 把所有Identity配置集中在这里
    services.AddDefaultIdentity<IdentityUser>(options => 
    {
        options.SignIn.RequireConfirmedAccount = true;
        // 密码规则配置
        options.Password.RequiredLength = 1;
        options.Password.RequireUppercase = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireDigit = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequiredUniqueChars = 5;
    })
    .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddControllersWithViews();
    services.AddRazorPages();
}

方法二:调整配置顺序,把Configure放在AddDefaultIdentity之后

如果你还是想单独用services.Configure<IdentityOptions>,就把这段代码移到AddDefaultIdentity之后,因为后执行的Configure会覆盖之前的默认配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();

    // 现在配置会覆盖AddDefaultIdentity的默认值
    services.Configure<IdentityOptions>(options =>
    {
        options.Password.RequiredLength = 1;
        options.Password.RequireUppercase = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireDigit = false;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequiredUniqueChars = 5;
    });

    services.AddControllersWithViews();
    services.AddRazorPages();
}

验证生效

修改完代码后,记得重启应用,然后测试注册页面:尝试输入1个包含大小写的密码,看看是否能通过验证(同时要满足5个唯一字符的要求哦)。

如果还是有问题,可以检查注册页面的视图模型有没有自定义的验证属性(比如[MinLength(6)]),不过默认的Identity注册页面是直接用IdentityOptions的规则,所以应该没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:52:58