gpt4 book ai didi

c# - ASP.Net Core MVC - 部分 View 的 Auth 上下文不同?

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:27 24 4
gpt4 key购买 nike

我有一个生成 2 个局部 View 的模型。

  • 一个局部 View 包含一个用于更改用户名的表单
  • 另一个包含用于更改密码的表单

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

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


更改用户名

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);
}
服务
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;
}


更改密码

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 Controller 吗?this.Authorization 是否出于某种原因对于每个局部 View 都不同?

最佳答案

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

关于c# - ASP.Net Core MVC - 部分 View 的 Auth 上下文不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55153989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com