-1

In a Asp.net Core project, I´m using the code below to change user name and email. But the property "User" in the controller does not update, just after logoff.

obs.: This "User" property is already defined by the framework in controller bases class, and it is a "ClaimsPrincipal" type.

Controller

    public async Task<IActionResult> Create(EditViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            var model = await _userManager.FindByIdAsync(CurrentUser.Id);
            model.UserName = viewModel.UserName;
            model.Email = viewModel.Email;

            await _userManager.UpdateAsync(model);

            //THIS ONE STILL HAS OLD VALUES ==============================
            Console.WriteLine(_userManager.GetUserName(User)); 

            //THIS ONE HAS NEWER VALUES ==================================
            model = await _userManager.FindByIdAsync(CurrentUser.Id);
            Console.WriteLine(model.UserName); 

            ...

I´m using this "User" property in my views, to display user informations, like this:

View

@inject UserManager<ApplicationUser> UserManager
...
<p>Hello: @UserManager.GetUserName(User)</p>
Beetlejuice
  • 4,292
  • 10
  • 58
  • 84

1 Answers1

5

This is likely because your current User is going to be stored in a fashion similar to a Claim (i.e. in memory) or Cookie to avoid frequent hits to the database and thus in order to pull the new values, you would need to log out and log back in to refresh these.

However, you could try following your code by calling the RefreshSignInAsync() method, which should handle this same behavior :

// Update your User
await _userManager.UpdateAsync(model);
// signInManager is an instance of SignInManager<ApplicationUser> and can be passed in via
// dependency injection
await signInManager.RefreshSignInAsync(existingUser);
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • 1
    This works, [but seemingly only for the currently logged in user](https://stackoverflow.com/q/51571852/590790), begging the question why the user can be passed at all then. If I pass a different user, the currently logged in user becomes logged in as that user instead. – Steven Jeuris Jul 30 '18 at 12:14