using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; using System.Threading; using System.Data.SqlClient; using System; using Dapper; using YepMarsCRM.Enterprise.DataBase.Model; using YepMarsCRM.Enterprise.DataBase.Data; namespace YepMarsCRM.Web.CustomProvider { public class DapperUsersTable { private readonly SqlConnection _connection; private readonly Sys_AccountData _sys_AccountData; public DapperUsersTable(SqlConnection connection) { _connection = connection; _sys_AccountData = new Sys_AccountData(); } private Sys_Account ApplicationUserToAccount(ApplicationUser user) { return new Sys_Account { Id = user.Id, UserName = user.UserName, PasswordHash = user.PasswordHash, Email = user.Email, EmailConfirmed = user.EmailConfirmed, PhoneNumber = user.PhoneNumber, PhoneNumberConfirmed = user.PhoneNumberConfirmed, LockoutEnd = user.LockoutEnd?.DateTime, LockoutEnabled = user.LockoutEnabled, AccessFailedCount = user.AccessFailedCount, }; } #region createuser public async Task<IdentityResult> CreateAsync(ApplicationUser user) { int rows = await _sys_AccountData.InsertAsync(ApplicationUserToAccount(user)); if (rows > 0) { return IdentityResult.Success; } return IdentityResult.Failed(new IdentityError { Description = $"Could not insert user {user.Email}." }); } #endregion public async Task<IdentityResult> DeleteAsync(ApplicationUser user) { //string sql = "DELETE FROM Sys_Account WHERE Id = @Id"; //int rows = await _connection.ExecuteAsync(sql, new { user.Id }); int rows = await _sys_AccountData.DeleteForPKAsync(ApplicationUserToAccount(user)); if (rows > 0) { return IdentityResult.Success; } return IdentityResult.Failed(new IdentityError { Description = $"Could not delete user {user.Email}." }); } public async Task<ApplicationUser> FindByIdAsync(Guid userId) { string sql = "SELECT * FROM Sys_Account WHERE Id = @Id;"; return await _connection.QuerySingleOrDefaultAsync<ApplicationUser>(sql, new { Id = userId }); } public async Task<ApplicationUser> FindByNameAsync(string userName) { string sql = "SELECT * FROM Sys_Account WHERE UserName = @UserName;"; return await _connection.QuerySingleOrDefaultAsync<ApplicationUser>(sql, new { UserName = userName }); //var user = new ApplicationUser() { UserName = userName, Email = userName, EmailConfirmed = false }; //user.PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(user, "test"); //return await Task.FromResult(user); } public async Task<IdentityResult> UpdateAsync(ApplicationUser applicationUser) { var user = ApplicationUserToAccount(applicationUser); var result = await _sys_AccountData.UpdateForPKAsync(user); if (result > 0) { return IdentityResult.Success; } return IdentityResult.Failed(new IdentityError { Description = $"Could not update user {user.Email}." }); } } }
三、使用UserManager、SignInManager验证操作
新建一个 AccountController 控制器 并在构造函数中获取 依赖注入的对象 UserManager 与 SignInManager 如下: