我想使用Microsoft.AspNetCore.Identity
,但没有EntityFramework
——我正在尝试使用我自己的IUserStore
实现。我还没有决定使用什么数据库,但我认为这对这个问题来说无关紧要。
相关类别,尽可能精简:
启动.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddUserStore<CustomUserStore<ApplicationUser>>()
.AddUserManager<CustomUserManager>();
}
应用程序用户:
public class ApplicationUser
{
public string UserName { get; set; }
public string Email { get; set; }
}
自定义用户商店:
public class CustomUserStore<TUser> : IUserStore<TUser> where TUser : ApplicationUser
{
private bool _disposed;
public async Task<IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
//Trying to hit a breakpoint here
throw new NotImplementedException();
}
//Other method implementations removed for brevity
void IDisposable.Dispose()
{
_disposed = true;
}
}
自定义用户管理器:
public class CustomUserManager : UserManager<ApplicationUser>
{
public CustomUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger)
: base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors,services,logger)
{
}
public override async Task<IdentityResult> CreateAsync(ApplicationUser user)
{
// Trying to hit a breakpoint here
return await this.Store.CreateAsync(user, new CancellationToken());
}
}
示例控制器:
[Route("api/example")]
public class ExampleController : Controller
{
private CustomUserManager _userManager;
public ExampleController(CustomUserManager userManager)
{
_userManager = userManager;
}
[Route("test")]
public void Test()
{
var user = new ApplicationUser { UserName = "something", Email = "somthingElse" };
_userManager.CreateAsync(user, "password");
}
}
当我点击我用来测试它的URL:api/example/test
时,CustomUserManager
中的构造函数会被点击,但CustomUserManager
中的CreateAsync
不会被点击,因此CustomUserStore
中没有任何内容被点击。
您在CustomUserManager
中重写CreateAsync(ApplicationUser user)
方法,但在Test()
方法中调用CreateAsync(ApplicationUser user, string password)
方法。
你调用了错误的方法。