ASP.Net核心MVC - 部分视图的Auth Context不同?

问题描述 投票:2回答:1

我有一个产生2个局部视图的模型。

  • 一个部分视图包含一个用于更改用户名的表单
  • 另一个包含更改密码的表单

两种形式都返回到UserController中的POST方法。每个部分,独立工作正常。但是,如果我更改用户名然后尝试更改密码,则Auth Context包含旧用户名,并且我遇到错误。

逻辑有点像这样......


Change Username

Controller
public async Task<ActionResult> ChangeUsername(ChangeUsernameViewModel model) {
    string oldUsername = model.OldUsername;
    string newUsername = model.NewUsername;

    User user = await this.UserService.GetUserById(this.Authorization.UserId);

    if (user != null)
    {
        // Update username in DB
        User user = await this.UserService.ChangeUsername(user, newUsername);

        // Update cookie
        this._owinContext.Authentication.SignIn(this.Authorization.ToClaimsIdentity());

        // Update ViewModel
        model.OldUsername = newUsername;
        model.NewUsername = string.Empty();
    }

    return View(model);
}
Service
public async Task<User> ChangeUsername(User user, string newUsername) {
    // Blah blah blah... Code to update user with new username
    // and save changes to DB which is then followed by:

    // Change claim in Auth Context
    this._authorization.RemoveValue(MyClaimType.Username);
    this._authorization.AddValue(MyClaimType.Username, newUsername);

    // At this point, I can see that the Auth Context
    // has been updated with the new username.

    return user;
}

Change Password

Controller
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model) {
    string oldPassword = model.oldPassword;
    string newPassword = model.newPassword;

    User user = await UserService.GetUserByLogin(this.Authorization.Username, oldPassword);

    // this is where the failure occurs, so I won't 
    // bother writing out the rest.

    // this.Authorization.Username is equal to "oldUsername" 
    // that we saw in the ChangeUsername method.
}

服务中的this._authorization不会带回控制器的this.Authorization吗?由于某种原因,this.Authorization对于每个局部视图是不同的吗?

c# asp.net-mvc
1个回答
0
投票

清除/重置/注销用户会话,使用用户或db提供的新数据重新加载会话数据信息

© www.soinside.com 2019 - 2024. All rights reserved.