2

我已经为使用 ASP.NET 5、MVC 6、EF 7 和 Identity 3 的项目实现了自定义 RoleStore 和自定义 UserStore。但是 - 我不太清楚如何配置身份以使用我的自定义 RoleStore 和自定义 UserStore 而不是通常的产品。如何重新配置​​系统以使用我的自定义类?

PS:我也有自定义用户和角色类。

解决方案

这就是我最终做的事情。首先,我从我的项目中卸载了“身份实体框架”包。这导致一些东西丢失,所以我重新实现了它们(阅读:从这里复制它们),并将它们放在“标准”命名空间中以表明它们没有被定制。我现在有一个“安全”命名空间,其中包含以下内容:

  • 标准
    • 身份角色.cs
    • IdentityRoleClaim.cs
    • 身份用户.cs
    • IdentityUserClaim.cs
    • IdentityUserLogin.cs
    • 身份用户角色.cs
  • BuilderExtensions.cs
  • IdentityDbContext.cs
  • 资源.resx
  • 角色.cs
  • 角色存储.cs
  • 用户.cs
  • 用户存储.cs

粗体显示的项目包含项目特定的功能。

允许我使用自定义商店的代码位于“BuilderExtensions”文件中,该文件包含以下类:

public static class BuilderExtensions
{
    public static IdentityBuilder AddCustomStores<TContext, TKey>(this IdentityBuilder builder)
        where TContext : DbContext
        where TKey : IEquatable<TKey>
    {
        builder.Services.TryAdd(GetDefaultServices(builder.UserType, builder.RoleType, typeof(TContext), typeof(TKey)));
        return builder;
    }

    private static IServiceCollection GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType)
    {
        var userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType);
        var roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType);
        var services = new ServiceCollection();
        services.AddScoped(
            typeof(IUserStore<>).MakeGenericType(userType),
            userStoreType);
        services.AddScoped(
            typeof(IRoleStore<>).MakeGenericType(roleType),
            roleStoreType);
        return services;
    }
}

然后,这允许我在 Startup.cs 文件中编写以下内容:

services.AddIdentity<User, Role>()
    .AddCustomStores<PrimaryContext, string>()
    .AddDefaultTokenProviders();

并且将使用自定义商店。请注意,PrimaryContext 是我的整个项目 DbContext 的名称。它继承自 IdentityDbContext。

讨论

我本可以保留“身份实体框架”包并保存自己复制“标准”命名空间的内容,但我选择不这样做,这样我可以使我的标识符保持简短和明确。

4

1 回答 1

1

查看此部分重新配置应用程序以使用ASP.NET 身份的自定义存储提供程序概述中的新存储提供程序

特别是“如果您的项目中包含默认存储提供程序,则必须删除默认提供程序并用您的提供程序替换它。”

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    var manager = new ApplicationUserManager(new YourNewUserStore(context.Get<ExampleStorageContext>()));
    ...
}
于 2016-04-26T21:56:08.163 回答