Programmatically refresh/update HttpContext.User

北城以北 提交于 2020-01-11 05:59:59

问题


I'm using FormsAuthentication for an ASP.NET site that has a master page that displays the current logged in user, Page.User.Identity.Name.

They can change their username in their settings, and when the do so, I update their cookie for them so they wont have to sign out/sign back in with a postback.

FormsAuthentication.SignOut();
FormsAuthentication.SetAuthCookie(username, false);

I'm probably being pretty nit-picky, but after they change their username the master page still displays their original username until they reload or load a different page.

Is there any way to programmatically update the current Page.User, so that their new username can be displayed during the same postback?


回答1:


Though MasterMax's suggestion is what I would do, you can actually update the Page.User via HttpContext.Current.User.

If you know the user's roles (or you aren't using role based authorization), you can take advantage of the System.Security.Principal.GenericPrincipal class:

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

HttpContext.Current.User = 
   new GenericPrincipal(new GenericIdentity(newUserName), roles);



回答2:


you could create an instance of your master page class, and make the property that you're setting for the username public, so that you can set that property right after your FormsAuthentication code.



来源:https://stackoverflow.com/questions/603838/programmatically-refresh-update-httpcontext-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!