【问题标题】:Programmatically refresh/update HttpContext.User以编程方式刷新/更新 HttpContext.User
【发布时间】:2009-03-02 20:19:32
【问题描述】:

我正在为一个 ASP.NET 站点使用 FormsAuthentication,该站点的母版页显示当前登录的用户 Page.User.Identity.Name。

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

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

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

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

【问题讨论】:

    标签: asp.net forms-authentication httpcontext


    【解决方案1】:

    虽然 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);
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-19
        相关资源
        最近更新 更多