我目前有一个针对完整.NET 框架的.NET 核心 Web 应用程序和一个包含我的 EF6 实现的.NET 4.6.1 类库项目。
我这两个目前正在合作。
现在我需要添加 Identity,但我需要自定义实现。 (如果重要的话,我正在建立一个现有的用户表,只关心本地登录)
所以在 4.6.1 类库项目中,我使用本指南创建了自定义标识 classes/stores/managers:https://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity
我坚持的部分是如何配置.NET 核心应用程序以使用 non-Core 版本的身份。
所有教程都有类似的配置
services.AddIdentity<ApplicationUser, ApplicationRole>(config => { })
.AddEntityFrameworkStores<ApplicationDbContext>();
和
app.UseIdentity();
但是这两种方法只存在于 Microsoft.AspNetCore.Identity 而不是 Microsoft.AspNet.Identity.Core,这就是类库所使用的。
.NET 核心应用程序应引用哪些框架? Startup.cs 配置应该是什么样的?
为了简单起见,我的所有自定义身份代码都与上面链接的文章完全相同。
Startup.cs 代码看起来像这样(引用了 AspNetCore.Identity)
services.AddIdentity<ApplicationUser, CustomRole>(config => { /* config */ })
.AddUserManager<ApplicationUserManager>()
.AddUserStore<CustomRoleStore>()
.AddDefaultTokenProviders();
样本控制器
public AccountController(ApplicationSignInManager signInManager)
{
_signInManager = signInManager;
}
尝试运行时出错
InvalidOperationException:类型 ApplicationUserManager 必须从 UserManager 派生。
1 回答
你应该严格区分两个 api:ASP NET Identity https://github.com/aspnet/AspNetIdentity和 ASP NET Core Identity https://github.com/aspnet/Identity
应引用 ASP NET 核心标识(Microsoft.AspNetCore)。
由于您要使用 EF6,因此需要将“Microsoft.AspNetCore.Identity.EntityFrameworkCore”(https://github.com/aspnet/Identity/tree/master/src/EF)移植到您自己的使用 EF6 的实现中。在此之后,您需要提供自己的
.AddEntityFrameworkStores<TDbContext>();
扩展方法。因此 Startup.cs 应该保持相同(除了使用,引用 AddEntityFrameworkStores,您需要指向您的移植的 lib 命名空间)。