I used this code for admin panel to changed password of customer by manager,I did not get any Error. but password not changed,
i got my coed from this
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult ChangeUserPassword(SetPasswordViewModel model,string userId)
{
if (ModelState.IsValid)
{
//var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
ApplicationUser appUser = db.Users.Find(userId);
var result = UserManager.ChangePasswordAsync(appUser, model.NewPassword);
if (result.IsCompleted)
{
var user = UserManager.FindById(User.Identity.GetUserId());
//var user = db.Users.Find(userId);
if (user != null)
{
//await SignInManager<,>.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageController.ManageMessageId.SetPasswordSuccess });
}
// AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
and in controller for change use this
public async Task<IdentityResult> ChangePasswordAsync(ApplicationUser Appuser, string newPassword)
{
var store = this.Store as Microsoft.AspNet.Identity.IUserPasswordStore<ApplicationUser,string>;
if (store == null)
{
var errors = new string[]
{
"Current UserStore doesn't implement IUserPasswordStore"
};
return IdentityResult.Failed(errors);
// return Task.FromResult(new IdentityResult(errors) { Succeeded = false });
}
var newPasswordHash = this.PasswordHasher.HashPassword(newPassword);
await store.SetPasswordHashAsync(Appuser, newPasswordHash);
await store.UpdateAsync(Appuser);
//return await Task.FromResult<IdentityResult>(IdentityResult.Success);
return IdentityResult.Success;
}
}
whats my mistake?
after update answer i use this method instead
[HttpPost]
public async Task<IdentityResult> ChangePasswordAsync(ApplicationUser appuserId, string newPassword)
{
ApplicationDbContext db = new ApplicationDbContext();
//var userr =await db.Users.FirstOrDefaultAsync(x => x.Id == appuserId.Id);
var newPasswordHash = this.PasswordHasher.HashPassword(newPassword);
db.Entry(Users).State = EntityState.Modified;
if (appuserId != null) appuserId.PasswordHash = newPasswordHash;
db.SaveChanges();
return IdentityResult.Success;
}
but had the same problem again
in IdentityModels.cs i had
public DbSet<CommonAction> CommonActions { get; set; }
public DbSet<PublicContent> PublicContents { get; set; }
public DbSet<MainSubject> MainSubjects { get; set; }
public DbSet<EducationLevel> EducationLevels { get; set; }
public DbSet<TimePeriod> TimePeriods { get; set; }
public DbSet<HelpType> HelpTypes { get; set; }
public DbSet<FinancialSupport> FinancialSupports { get; set; }
public DbSet<LinksStatistic> LinksStatistics { get; set; }
public DbSet<SlideOfCommonAction> SlideOfCommonActions { get; set; }
in normal model IdentityModel User is not register as DbSet
()
You're not awaiting ChangePasswordAsync, you're just checking if it's completed or not. Which may result in the View being returned before the password has been changed.
Then you should try to use async/await all the way, if possible. That means that your action should be async as well.
[HttpPost]
[ValidateAntiForgeryToken]
public virtual async Task<ActionResult> ChangeUserPassword(SetPasswordViewModel model,string userId)
{
if (ModelState.IsValid)
{
//var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
ApplicationUser appUser = db.Users.Find(userId);
// await the result.
var result = await UserManager.ChangePasswordAsync(appUser, model.NewPassword);
if (result.Succeeded) // Or whatever you're expecting.
{
var user = UserManager.FindById(User.Identity.GetUserId());
//var user = db.Users.Find(userId);
if (user != null)
{
//await SignInManager<,>.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageController.ManageMessageId.SetPasswordSuccess });
}
// AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
Update after comments:
The entity type DbSet`1 is not part of the model for the current context
db.Entry(Users).State = EntityState.Modified;
This is when EF cannot connect your model to an entity in the context. Without seeing the code, it's hard to say exactly why. But it could be that your're missing a DbSet in your context.
Have you configured your UserManager correctly? Does the other UserManager actions work?
Try debugging and see where it crashes.
Related
I run into another problem. I have a UserRole domain class which takes UserID and RoleID
public class User_Role
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
//nav prop
public User User { get; set; }
public Guid RoleId { get; set; }
//nav prop
public Role Role { get; set; }
}
Roles have 2 types Reader and Admin. I need them for authentication which I will implement later.
The problem is when I added a "Reader" I can add it again and again. I understand that I need to validate user_role. This is my User_role controller
[Route("api/[controller]")]
[ApiController]
public class UserRoleController : ControllerBase
{
public readonly IUserRepository _userRepository;
public readonly IRoleRepository _roleRepository;
public readonly IUserRoleRepository _userRoleRepository;
public UserRoleController(IUserRepository userRepository, IRoleRepository IRoleRepository,
IUserRoleRepository userRoleRepository)
{
_userRepository = userRepository;
_roleRepository = IRoleRepository;
_userRoleRepository = userRoleRepository;
}
[HttpGet]
public async Task<IActionResult> GetAllUserRoles()
{
var userRoleDomain = await _userRoleRepository.GetAllAsync();
return Ok(userRoleDomain);
}
[HttpGet]
[Route("{userRoleId:guid}")]
[ActionName("GetUserRoleById")]
public async Task<IActionResult> GetUserRoleById(Guid userRoleId)
{
var userRoleDomain = await _userRoleRepository.GetUserRoleByIdAsync(userRoleId);
if(userRoleDomain == null)
{
return NotFound();
}
var UserRoleDto = userRoleDomain.ConvertToDto();
return Ok(UserRoleDto);
}
[HttpPost]
public async Task<IActionResult> AddUserRole([FromBody]AddUserRoleRequest addUserRoleRequest)
{
if(!(await ValidateAddUserRoleAsync(addUserRoleRequest)))
{
return BadRequest(ModelState);
}
//CheckIfRoleExist
var userRoleDomain = new User_Role
{
RoleId = addUserRoleRequest.RoleId,
UserId = addUserRoleRequest.UserId
};
userRoleDomain = await _userRoleRepository.AddUserRoleAsync(userRoleDomain);
var userRoleDto = userRoleDomain.ConvertToDto();
return CreatedAtAction(nameof(GetUserRoleById), new { userRoleId = userRoleDto.Id}, userRoleDto);
}
[HttpDelete]
[Route("{userRoleId:guid}")]
public async Task<IActionResult> DeleteUserRole(Guid userRoleId)
{
var userRoleDomain = await _userRoleRepository.DeleteAsync(userRoleId);
if(userRoleDomain == null)
{
return NotFound();
}
var userRoleDto = userRoleDomain.ConvertToDto();
return Ok(userRoleDto);
}
[HttpPut]
[Route("{userRoleId:guid}")]
public async Task<IActionResult> UpdateUserRole([FromRoute]Guid userRoleId,
[FromBody]UpdateUserRoleRequest updateUserRoleRequest)
{
if(!(await ValidateUpdateUserRoleAsync(updateUserRoleRequest)))
{
return BadRequest(ModelState);
}
var userRoleDomain = new User_Role()
{
Id = userRoleId,
UserId = updateUserRoleRequest.UserId,
RoleId = updateUserRoleRequest.RoleId
};
userRoleDomain = await _userRoleRepository.UpddateAsync(userRoleId, userRoleDomain);
if(userRoleDomain == null)
{
return NotFound();
}
var userRoleDto = userRoleDomain.ConvertToDto();
return Ok(userRoleDto);
}
#region Validation methods
private async Task<bool> ValidateAddUserRoleAsync(AddUserRoleRequest addUserRoleRequest)
{
var user = await _userRepository.GetAsyncByIdWithRoles(addUserRoleRequest.UserId);
if (user == null)
{
ModelState.AddModelError(nameof(addUserRoleRequest.UserId),
$"{nameof(addUserRoleRequest.UserId)} UserId is invalid");
}
var role = await _roleRepository.GetAsync(addUserRoleRequest.RoleId);
if(role == null)
{
ModelState.AddModelError(nameof(addUserRoleRequest.RoleId),
$"{nameof(addUserRoleRequest.RoleId)} RoleId is invalid");
}
if(ModelState.ErrorCount > 0)
{
return false;
}
return true;
}
private async Task<bool> ValidateUpdateUserRoleAsync(UpdateUserRoleRequest updateUserRoleRequest)
{
var user = await _userRepository.GetUserByIdASync(updateUserRoleRequest.UserId);
if(user == null)
{
ModelState.AddModelError(nameof(updateUserRoleRequest.UserId),
$"{nameof(updateUserRoleRequest.UserId)} UserId is invalid");
}
var role = await _roleRepository.GetAsync(updateUserRoleRequest.RoleId);
if(role == null)
{
ModelState.AddModelError(nameof(updateUserRoleRequest.RoleId),
$"{nameof(updateUserRoleRequest.RoleId)} RoleId is invalid");
}
if(ModelState.ErrorCount > 0)
{
return false;
}
return true;
}
private async Task<bool> CheckIfRoleExist(AddUserRoleRequest addUserRoleRequest)
{
}
#endregion
}
I am thinking to validate this in my CheckIfRoleExist function. How do I check if this type of role is already added with a specific userId?
Adding call to repository
public async Task<bool> CheckIfAlreadyExistAsync(User_Role userRole)
{
var userRoleExist = await _webApiDbContext.User_Roles.AnyAsync(u => u.RoleId == userRole.RoleId && u.UserId == userRole.UserId);
if(userRoleExist != null)
{
return true;
}
return false;
}
Figured out something like this
private async Task<bool> CheckIfRoleExist(AddUserRoleRequest addUserRoleRequest)
{
var user = await _userRepository.GetAsyncByIdWithRoles(addUserRoleRequest.UserId);
if(user == null)
{
return false;
}
foreach(var roleAdded in user.UserRoles)
{
if(roleAdded.RoleId == addUserRoleRequest.RoleId)
{
ModelState.AddModelError(nameof(addUserRoleRequest.RoleId),
$"{nameof(addUserRoleRequest.RoleId)} user already have this role");
}
}
if (ModelState.ErrorCount > 0)
{
return false;
}
return true;
}
If you have cleaner answer dont be afraid to post it:)
I have a controller with 2 actions containing identical code. But i'm having trouble reusing it from a separate function, without resorting to returning null and checking return values. The actions are for logging in and for resending a two factor toke.
2 actions (Login and Resend)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model)
{
if (!ModelState.IsValid) return View();
var user = await userManager.FindByNameAsync(model.UserName);
if(!(user != null && !await userManager.IsLockedOutAsync(user)))
{
ModelState.AddModelError("", "Invalid UserName or Password");
return View();
}
if(!await userManager.CheckPasswordAsync(user, model.Password))
{
ModelState.AddModelError("", "Invalid UserName or Password");
return View();
}
// can this be improved?
var r = await SendTwoFactor(user);
if(r != null) return r; // error or redirect or no two factor?
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Resend(ResendModel model)
{
var result = await HttpContext.AuthenticateAsync(IdentityConstants.TwoFactorUserIdScheme);
if (!result.Succeeded)
{
return RedirectToAction(nameof(Login)); // expired
}
var user = await userManager.FindByIdAsync(result.Principal.FindFirstValue("sub"));
if (user == null)
{
return RedirectToAction(nameof(Login)); // invalid
}
await HttpContext.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);
// can this be improved?
var r = await SendTwoFactor(user);
if(r != null) return r; // error or redirect or no two factor?
...
return RedirectToAction("...");
}
then the re-used code looks something like this:
SendTwoFactor
private async Task<IActionResult> SendTwoFactor(IdentityUser user)
{
if(!await userManager.GetTwoFactorEnabledAsync(user)) return null;
var d = ...;
if(!d)
{
ModelState.AddModelError("", "... d");
return View();
}
// determine preferred two factor method
// send two factor token
return RedirectToAction("...");
}
Does anyone have a good pattern to improve this?
This would be my aproach
First of all, we need to define interface with the 'common' elements inside FooModel and Foo2Model that would be used in common code like this:
public interface iFoo
{
int Id { get; set; }
string Product_name{ get; set; }
}
public class Foo : iFoo
{
public string OtherThings { get; set; }
public int Id { get; set; }
public string Product_name { get; set; }
}
public class Foo2 : iFoo
{
public string OtherThings2 { get; set; }
public int Id { get; set; }
public string Product_name_nv { get; set; }
}
Then we can make a private function like this:
private async Task<IActionResult> identicalFunction<T>(T model) where T : iFoo
{
c = ...;
if(c)
{
d = ...;
if(!d)
{
ModelState.AddModelError("", "... d");
return View();
}
... // a lot more code similar code that can exit early
return RedirectToAction("...");
}
// Note that I included the last return inside this function
return RedirectToAction("...");
}
And then change
// identical code
return RedirectToAction("...");
into:
return await identicalFunction(model);
I'm pretty new to asp.net and c# and I recently ran into this problem which I can't seem to work around.
Basically, I inherited the IdentityUser class like so, and added my own attributes:
public class ApplicationUser : IdentityUser
{
[ForeignKey("Wallet")]
public int WalletID { get; set; }
[ForeignKey("Portfolio")]
public int PortfolioID { get; set; }
public virtual Wallet Wallet { get; set; }
public virtual Portfolio Portfolio { get; set; }
}
Now, the problem occurs when I try to register using the auto generated register page because the fields WalletID and PorfolioID are
not initialized. A few things I tried inside the Register.cshtml.cs code for the Identity Account were:
Creating a new Wallet and Portfolio using :
Wallet w = new Wallet(); Portfolio p = new Portfolio();
and assigning their id to corresponding attributes inside the ApplicationUser. The problem with this is that I don't know how to get the instance of the database context so they are not added to the database and therefore violate the ForeignKey constraint.
Tried to get instance of WalletController and PortfolioController, then call the Create() methods from inside the Register.cshtml.cs, but to no avail. I also read that this is bad practice and should be avoided.
Essentially, what I want to do is, when someone registers, create an instance of Portfolio and Wallet, add them to my database, assign their IDs to corresponding attributes inside the ApplicationUser and proceed with the registraton.
What is the best way to solve this?
The auto-generated Register.cshtml.cs:
using...
namespace CryptoSimulation.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}
The auto-generated WalletController (PortfolioController is pretty much the same):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using CryptoSimulation.Data;
using CryptoSimulation.Models;
namespace CryptoSimulation.Controllers
{
public class PortfolioController : Controller
{
private readonly ApplicationDbContext _context;
public PortfolioController(ApplicationDbContext context)
{
_context = context;
}
// GET: Portfolio
public async Task<IActionResult> Index()
{
return View(await _context.Portfolio.ToListAsync());
}
// GET: Portfolio/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var portfolio = await _context.Portfolio
.FirstOrDefaultAsync(m => m.PortfolioID == id);
if (portfolio == null)
{
return NotFound();
}
return View(portfolio);
}
// GET: Portfolio/Create
public IActionResult Create()
{
return View();
}
// POST: Portfolio/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("PortfolioID")] Portfolio portfolio)
{
if (ModelState.IsValid)
{
_context.Add(portfolio);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(portfolio);
}
// GET: Portfolio/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var portfolio = await _context.Portfolio.FindAsync(id);
if (portfolio == null)
{
return NotFound();
}
return View(portfolio);
}
// POST: Portfolio/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("PortfolioID")] Portfolio portfolio)
{
if (id != portfolio.PortfolioID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(portfolio);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PortfolioExists(portfolio.PortfolioID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(portfolio);
}
// GET: Portfolio/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var portfolio = await _context.Portfolio
.FirstOrDefaultAsync(m => m.PortfolioID == id);
if (portfolio == null)
{
return NotFound();
}
return View(portfolio);
}
// POST: Portfolio/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var portfolio = await _context.Portfolio.FindAsync(id);
_context.Portfolio.Remove(portfolio);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PortfolioExists(int id)
{
return _context.Portfolio.Any(e => e.PortfolioID == id);
}
}
}
This is not an answer but my guess. I cannot comment on SO yet. My guess is that the code is aware of your foreign keys but the DB is not. You can add migration and update database.
Adding migration in Package Manager in VS using add-migration command will generate all changes. update database will actually apply the changes to the DB. You can look at the Up() method in the generated migration to see if the foreign keys are reflected properly
Documentation for migration: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli
I don't Want Modified UserPassword when it's null or empty ,I search for long time but it's doesn't work
Would you give me some advice ?
public async Task<IActionResult> Edit(int ID, [Bind("UserId,UserPassword,Username,Fullname,Nickname,Sex,Status,Email,Tel,Mobile,Address,Province,City,PostCode,UserType")] User user)
{
if (ID != user.UserId)
{
return NotFound();
}
if (ModelState.IsValid)
{
if (string.IsNullOrEmpty(user.UserPassword))
{
context.Attach(user);
context.Entry(user).Property("UserPassword").IsModified = false;
}
else
{
user.UserPassword = main.Md5(user.UserPassword);
}
context.Update(user);
await context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(user);
}
Here is cshtml
enter image description here
Try the below code:
context.Update(user);
context.Entry<User>(user).Property(x => x.UserPassword).IsModified = false;
context.SaveChanges();
The Update method marks all the properties as modified, you should change the state of IsModified after it.
You can refer to https://github.com/dotnet/efcore/issues/6849
Instead of receiving user in your action , create a viewmodel and use that for update your user info.
Example:
public class UserViewModel {
public string UserId { get; set; }
public string UserPassword { get; set;}
... // other properties
}
public async Task <IActionResult> Edit(int ID, UserViewModel viewModel) {
if (ID != viewModel.UserId) {
return NotFound();
}
if (ModelState.IsValid) {
var user = context.Users.FindAsync(viewModel.UserId);
user.Password = !string.IsNullOrEmpty(viewModel.Password) ? main.Md5(viewModel.Password) : user.Password;
// update other properties here
await context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(user);
}
I am doing custom asp.net identity and not using asp.net inbuilt tables.I have successfully created user with implementing custom CreateAsync
Now i want to update user with new encrypted password and so i am not getting how to provide custom implementation of UpdateAsync method.
This is my table:
User : Id,Name,EmailId,Password,Statistics,Salary
Model:
public class UserModel : IUser
{
public string Id { get; set; }
public string Name { get; set; }
public string EmailId { get; set; }
public string Password { get; set; }
public int Salary { get; set; }
}
My custom class which implements IUserstore:
public class UserStore : IUserStore<UserModel>, IUserPasswordStore<UserModel>
{
private readonly MyEntities _dbContext;
private readonly HttpContext _httpContext;
// How to implement this method for updating only user password
public Task UpdateAsync(UserModel user)
{
throw new NotImplementedException();
}
public Task CreateAsync(UserModel user)
{
return Task.Factory.StartNew(() =>
{
HttpContext.Current = _httpContext ?? HttpContext.Current;
var user = _dbContext.User.Create();
user.Name = user.Name;
user.EmailId = user.EmailId;
user.EmailAddress = user.Email;
user.Password = user.Password;
_dbContext.Users.Add(dbUser);
_dbContext.SaveChanges();
});
}
public Task SetPasswordHashAsync(UserModel user, string passwordHash)
{
return Task.Factory.StartNew(() =>
{
HttpContext.Current = _httpContext ?? HttpContext.Current;
var userObj = GetUserObj(user);
if (userObj != null)
{
userObj.Password = passwordHash;
_dbContext.SaveChanges();
}
else
user.Password = passwordHash;
});
}
public Task<string> GetPasswordHashAsync(UserModel user)
{
//other code
}
}
Controller:
public class MyController : ParentController
{
public MyController()
: this(new UserManager<UserModel>(new UserStore(new MyEntities())))
{
}
public UserManager<UserModel> UserManager { get; private set; }
[HttpPost]
public async Task<JsonResult> SaveUser(UserModel userModel)
{
IdentityResult result = null;
if (userModel.Id > 0) //want to update user with new encrypted password
result = await UserManager.UpdateAsync(user);
else
result = await UserManager.CreateAsync(userModel.EmailId, userModel.Password);
}
}
Not sure if this is what your looking for...
public Task UpdateAsync(UserModel model)
{
var user = _dbContext.User.Find(x => x.id == model.id);
user.Password = model.Password;
_dbContext.SaveChanges();
return Task.CompletedTask;
}
It Will get the specific record and Update the password and then save the record.
Edit
Since the password is not getting encrypted i added code to take that string and leave the model as it is, this extension method will encrypt the value of password, i have not test this but i am sure it will work.
user.Password = model.Password.EncryptPassword(EncryptKey);
Extension methods to encrypt password
Sometime back, I created a complete wrapper over .NET Identity and code can be found here. It might be helpful for you. You can also find nuget here. I also explained the library in a blog here.