Aktualizacja danych Web API

0

Witam mam 2 metody napisane w Web API do wyświetlania (GetUserProfile) i aktualizacji danych użytkownika (ChangeProfile). Metoda ChangeProfile działa poprawnie, ponieważ w bazie danych po aktualizacji dane są zmienione. Problem jest z wyświetleniem zaktualizowanych danych, ponieważ po updacie danych metoda GetUserProfile zwraca nie zmienione dane. Dopiero wyłączenie i włączenie aplikacji od nowa wyświetli zmienione dane.

   [HttpGet]
        [Route("api/GetUserProfile")]
        public AccountModel GetUserProfile()
        {
            var identityClaims = (ClaimsIdentity)User.Identity;
            IEnumerable<Claim> claims = identityClaims.Claims;
            AccountModel model = new AccountModel()
            {
                UserName = identityClaims.FindFirst("Username").Value,
                Email = identityClaims.FindFirst("Email").Value,
                FirstName = identityClaims.FindFirst("FirstName").Value,
                LastName = identityClaims.FindFirst("LastName").Value,
                LoggedOn = identityClaims.FindFirst("LoggedOn").Value
            };
            return model;
        }
        [HttpPost]
        [Route("api/ChangeProfile")]
        [ResponseType(typeof(AccountModel))]
        public async Task<IHttpActionResult> ChangeProfile([FromBody]AccountModel model)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var manager = new UserManager<ApplicationUser>(userStore);
            var user = await manager.FindByNameAsync(model.UserName);
            if (user != null)
            {
                user.FirstName = model.FirstName;
                user.LastName = model.LastName;
                user.Email = model.Email;
                
                IdentityResult result = await manager.UpdateAsync(user);
                return Ok(model);
                
            }
            else
            {
                return NotFound();
            }
        }

Dla przykładu zmieniłem imię i nazwisko ChangeProfile.PNG, w bazie danych dane zostały zmienione: DataInDatabase.PNG, a metoda GetUserProfile() dalej zwraca nie zmienione dane: DataNotUpdated.PNG
Front-end został napisany w Angularze.
Serwis:

  getUserProfile() {
    return this.http.get(this.rootUrl + '/api/GetUserProfile',
    {headers: new HttpHeaders({'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userToken'))})});
  }
  updateProfile(userData) {
    const profile = {
      Username: userData.username,
      Email: userData.email,
      FirstName: userData.firstName,
      LastName: userData.lastName,
    };
    const reqHeader = new HttpHeaders({'Content-Type': 'application/json'});
    return this.http.post(this.rootUrl + '/api/ChangeProfile', profile, {headers: reqHeader});
  }

Klasa komponentu:

export class AccountComponent implements OnInit {
  userData: any;
  profileForm: FormGroup;
  constructor(private formBuilder: FormBuilder, private authenticationService: AuthenticationService, private router: Router) { }

  ngOnInit() {
    this.authenticationService.getUserProfile().subscribe( (data: any) => {
      this.userData = data;
      this.profileForm.setValue({
       username: data.UserName,
       email: data.Email,
       firstName: data.FirstName,
       lastName: data.LastName
       });
      console.log(data);
    });
     this.formInitBuilder();
  }
  formInitBuilder() {
    this.profileForm = this.formBuilder.group ({
      username: [ '' ],
      email: [ '' ],
      firstName: [ '' ],
      lastName: [ '']
    });
  }
  onSubmit(registrationForm: FormGroup) {
    if (registrationForm.valid) {
    this.authenticationService.updateProfile(this.profileForm.value).
     subscribe(() => {
      this.router.navigate(['/home']);
      });
    }
  }
1

Claimsy są zwyczajowo przechowywane wewnątrz tokenu po stronie użytkownika, więc jak chcesz aktualne dane to najłatwiej byłoby zaczytywać je z bazy a nie z claimsów w metodzie GetUserProfile.

1 użytkowników online, w tym zalogowanych: 0, gości: 1