简体   繁体   中英

Update current user attributes on .net C#

I started a .net web forms project, the template already allows users to login and register, On the manage page there is an option to reset password. how can I add options to update FirstName and LastName?

This is the code to create a new user:

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); 
        var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text, FirstName = FirstName.Text, LastName = LastName.Text, PhoneNumber = PhoneNumber.Text };
        IdentityResult result = manager.Create(user, Password.Text);
        if (result.Succeeded)
        {
            signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);  //not needed
            IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); //not needed
        }
        else 
        {
            ErrorMessage.Text = result.Errors.FirstOrDefault();
        }

this is how the form looks like:

管理表格

This is how I solved it: hope it helps anybody.

var currentUserId = HttpContext.Current.User.Identity.GetUserId();
        var context = new ApplicationDbContext();
        var user = context.Users.FirstOrDefault(u => u.Id == currentUserId);

        if (user != null)
        {
            if (FirstName.Text != "")   user.FirstName = FirstName.Text;
            if (LastName.Text != "")    user.LastName = LastName.Text;
            if (PhoneNumber.Text != "") user.PhoneNumber = PhoneNumber.Text;
            if(Email.Text != "")        user.Email = Email.Text;

        }            

        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        var result = userManager.Update(user);
        context.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM