【问题标题】:Intended way of accessing options in custom ASP.NET Core Identity implementation在自定义 ASP.NET Core Identity 实现中访问选项的预期方式
【发布时间】:2016-09-14 08:58:48
【问题描述】:

我用自己的一组选项制作了一个自定义 PasswordValidator:

class MyValidator : Identity.PasswordValidator<TUser>
{
    Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password)
    {
        var options = // retrieve options
        if (options.CustomRule.Matches(password))
        // etc
    }
}

class MyPasswordOptions : Identity.PasswordOptions
{
    object CustomRule { get; set; }
}

现在我想在 MyValidator 中访问 MyPasswordOptions 的一个实例。例如,我可以:

  • 只需像任何选项类一样在 Startup.cs 中注册该类,并将其注入到 MyValidator 的构造函数中;
  • 将 MyPasswordOptions 类的实例传递给 services.AddIdentity() 中的 options.Password 属性,并在 MyValidator 的构造函数中注入 IdentityOptions。

然而,Microsoft 的原始实现通过 UserManager 的内部属性访问选项,这对我来说似乎是最好的选择,如果它不是内部的。

问题: Microsoft 在自定义实现中访问 Asp Identity Core 中的选项的预期方式是什么?说,我没有自定义选项类。如果不注入它们,我仍然无法轻松访问 MyValidator 类中的 IdentityOptions。而原来的类(Identity.PasswordValidator)可以。

【问题讨论】:

    标签: asp.net-core asp.net-identity-3


    【解决方案1】:

    在源代码中通过UserManager检索:

    manager.Options.Password
    

    这适用于获取默认选项,对于自定义选项,我认为您需要注册并解决它。

    source code

    【讨论】:

    • 可悲的是,选项是一个内部属性。如果我将它转换为我自己的类,它会适用于自定义选项。
    • 哦,我明白了,你是对的。但即使有可能,您也无法将其转换为您自己的班级。因为您不能将基类转换为派生类。看来您必须注入选项。我会使用单独的自定义选项而不是派生的。
    • @ademcaglin 如何注入我的自定义IdentityOptionsUserManager 上没有 .AddIdentityOptions() 扩展方法!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多