gpt4 book ai didi

c# - 在 ASP.NET 5 中使用自定义 UserStore 和 RoleStore

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:12 26 4
gpt4 key购买 nike

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

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

解决方案

这就是我最终做的事情。首先,我从我的项目中卸载了“Identity Entity Framework”包。这发送了一些丢失的东西,所以我重新实现了它们(阅读:从 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”命名空间的内容,但我选择不这样做,这样我可以保持我的标识符简短和明确。

最佳答案

查看此部分在 Overview of Custom Storage Providers for ASP.NET Identity 中重新配置应用程序以使用新的存储提供程序

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

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
var manager = new ApplicationUserManager(new YourNewUserStore(context.Get<ExampleStorageContext>()));
...
}

关于c# - 在 ASP.NET 5 中使用自定义 UserStore 和 RoleStore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36866933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com