【发布时间】:2016-08-20 09:36:06
【问题描述】:
我已经为使用 ASP.NET 5、MVC 6、EF 7 和 Identity 3 的项目实现了自定义 RoleStore 和自定义 UserStore。但是 - 我不太清楚如何配置身份以使用我的自定义 RoleStore 和自定义 UserStore 而不是通常的产品。如何重新配置系统以使用我的自定义类?
PS:我也有自定义的用户和角色类。
解决方案
这就是我最终要做的。首先,我从我的项目中卸载了“身份实体框架”包。这导致缺少一些东西,所以我重新实现了它们(阅读:从here 复制它们),并将它们放在“标准”命名空间中以表明它们没有被定制。我现在有一个“安全”命名空间,其中包含以下内容:
- 标准
- IdentityRole.cs
- IdentityRoleClaim.cs
- IdentityUser.cs
- IdentityUserClaim.cs
- IdentityUserLogin.cs
- IdentityUserRole.cs
- BuilderExtensions.cs
- IdentityDbContext.cs
- Resources.resx
- Role.cs
- RoleStore.cs
- User.cs
- UserStore.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。
讨论
我本可以保留“Identity Entity Framework”包并避免自己复制“Standard”命名空间的内容,但我选择不这样做,这样我可以使我的标识符保持简短和明确。
【问题讨论】:
标签: c# asp.net-core-mvc entity-framework-core asp.net-identity-3