1、添加用戶ide
public ReturnResult Add(JObject jo) { var returnResult = new ReturnResult(); string userId = jo.GetValue("Id").ToString(); string account = jo.GetValue("Account").ToString(); string password = jo.GetValue("Password").ToString(); string token = jo.GetValue("TokenKey").ToString(); using (var serviceProvider = BaseLogic.GetServiceProvider()) { using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) { var context = scope.ServiceProvider.GetService<ApplicationDbContext>(); var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>(); var userModel = userMgr.FindByNameAsync(account).Result; if (userModel == null) { userModel = new ApplicationUser { Id = userId, UserName = account }; var result = userMgr.CreateAsync(userModel, password).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } result = userMgr.AddClaimsAsync(userModel, new Claim[] { new Claim(JwtClaimTypes.Name, account), }).Result; if (!result.Succeeded) { throw new Exception(result.Errors.First().Description); } } else { userMgr.ResetPasswordAsync(userModel, token, password); } } } returnResult.Success = true; returnResult.Message = "操做成功"; return returnResult; }
2、刪除用戶ui
public ReturnResult Delete(JObject jo) { var returnResult = new ReturnResult(); string account = jo.GetValue("Account").ToString(); using (var serviceProvider = BaseLogic.GetServiceProvider()) { using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) { var context = scope.ServiceProvider.GetService<ApplicationDbContext>(); var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>(); var userModel = userMgr.FindByNameAsync(account).Result; if (userModel != null) { var claim = userMgr.GetClaimsAsync(userModel); if (claim.Result != null) { var deleteClaimsResult = userMgr.RemoveClaimsAsync(userModel, claim.Result); if (!deleteClaimsResult.Result.Succeeded) { returnResult.Success = false; returnResult.Message = string.Join(',', deleteClaimsResult.Result.Errors.ToList().Select(c => c.Description).ToList()); } } var deleteUserResult = userMgr.DeleteAsync(userModel); if (!deleteUserResult.Result.Succeeded) { returnResult.Success = false; returnResult.Message = string.Join(',', deleteUserResult.Result.Errors.ToList().Select(c => c.Description).ToList()); } } } } returnResult.Success = true; returnResult.Message = "操做成功"; return returnResult; }
3、遇到的坑坑坑坑(折騰了我一個多小時)spa
result = userMgr.AddClaimsAsync(userModel, new Claim[] { new Claim(JwtClaimTypes.Name, account), }).Result;
上面標紅的:code
JwtClaimTypes
雖然是引用的:IdentityModel,但不能在nuget直接添加這個引用,要添加IdentityServer4這個引用,添加了IdentityServer4就自動會有IdentityModel。