从DataAccess层访问ASP.NET标识数据

时间:2016-06-21 12:11:00

标签: asp.net asp.net-identity

我有一个使用MVC-WebApi,Owin,ASP.NET Identity和EntityFramework的n层解决方案。我使用示例Identity代码作为启动程序,并向ApplicationUser添加了一些自定义属性。我还配置了所有类来使用Guids for Identity值。到目前为止一切都很好。

当我想将示例代码中的IdentityConfig和IdentityModel文件从MVC项目移出到DataAccess项目时,我开始遇到困难。这些文件定义了几个关键类,如ApplicationUserManager,ApplicationRoleManager等。在ApplicationDbInitializer中,有一些代码可以使用当前的HttpContext获取ApplicationUserManager和ApplicationRoleManager,以便为数据库设定种子。似乎没有必要要求HttpContext为数据库设定种子。此外,我还将很快添加其他后台进程,这些进程需要在没有HttpContext相关的情况下从业务层访问Identity数据,所以我现在想要删除该依赖项。

我在这个主题ASP Identity - Accessing HttpContext on a reference library上看到了Q& A,但最好的答案很简单。我试过替换

var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();

var userManager = new ApplicationUserManager(new ApplicationUserStore(db));
var roleManager = new ApplicationRoleManager(new RoleStore<IdentityRole, Guid, IdentityUserRole>(db)); 
但是,这真的导致了一个兔子洞。除非我定义了每个Identity类的自定义实现并为它们实现了接口,否则代码将无法编译。它需要以下所有内容(可能更多,我没有完成它)

  • ApplicationUserRole:IdentityUserRole
  • ApplicationRole:IdentityRole,IRole
  • ApplicationUserClaim:IdentityUserClaim
  • ApplicationUserLogin:IdentityUserLogin

和IRole需要完全实现,我不知道该怎么做。

我在这一点上停了下来,因为感觉应该有一个更简单的方法或一些我可以看到的示例代码。我真的不需要在ApplicationUser之外定制任何东西。我是走在正确的道路上还是我的直觉,还有更好的方法吗?

0 个答案:

没有答案