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

发布于 2024-07-14 05:45:42 字数 386 浏览 5 评论 0原文

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

他们可以在设置中更改用户名,当这样做时,我会为他们更新 cookie,这样他们就不必通过回发注销/重新登录。

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

累赘 2024-07-21 05:45:42

虽然MasterMax的建议是我会做的,但您实际上可以通过HttpContext.Current.User更新Page.User

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

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

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

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);
活泼老夫 2024-07-21 05:45:42

您可以创建母版页类的实例,并将为用户名设置的属性设置为公共,以便您可以在 FormsAuthentication 代码之后立即设置该属性。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文