以编程方式刷新/更新HttpContext.User

4 asp.net forms-authentication httpcontext

我正在使用FormsAuthentication用于ASP.NET站点,该站点具有显示当前登录用户的主页,Page.User.Identity.Name.

他们可以在他们的设置中更改他们的用户名,当这样做时,我会为他们更新他们的cookie,这样他们就不必签回/用回发签到.

FormsAuthentication.SignOut();
FormsAuthentication.SetAuthCookie(username, false);
Run Code Online (Sandbox Code Playgroud)

我可能非常挑剔,但在他们更改用户名后,母版页仍会显示其原始用户名,直到他们重新加载或加载不同的页面.

有没有办法以编程方式更新当前的Page.User,以便在同一回发期间显示他们的新用户名?

Joh*_*sch 6

虽然MasterMax的建议是我要做的,但你可以实际更新Page.User通道HttpContext.Current.User.

如果您知道用户的角色(或者您没有使用基于角色的授权),则可以利用System.Security.Principal.GenericPrincipal该类:

string newUsername = "New Username";
string[] roles = new string[] {"Role1", "Role2"};

HttpContext.Current.User = 
   new GenericPrincipal(new GenericIdentity(newUserName), roles);
Run Code Online (Sandbox Code Playgroud)