在ASP.NET WebPages中使用FormsAuthentication

时间:2011-07-18 10:09:47

标签: c# .net asp.net authentication razor

我正在网站管理员的网络应用中设置FormsAuthentication。这个问题与Using FormsAuthentication有关 - 我现在的问题是;当管理员“成为现有用户”时,WebSecurity.CurrentUserId是否已填充他已成为用户的当前用户ID,或者它是否仍包含管理员的当前用户ID?

如果是后者,我们如何才能使WebSecurity.CurrentUserId返回他当前模仿的用户的用户ID?

2 个答案:

答案 0 :(得分:2)

@{
    if(Roles.IsUserInRole("Administrator")) 
    {   
        FormsAuthentication.SetAuthCookie(  
            "joe@harry.com",   
            false
        );
        Response.Redirect("~/Account/Page.cshtml");
    }
}
<!DOCTYPE html>
<html lang="en">
    <body>
        <p>You are now no longer an "admin", but user: @WebSecurity.CurrentUserId</p>
    </body>
</html>

以上代码有效。 WebSecurity.CurrentUserId的输出不再是Admin的用户ID,而是他刚刚成为的用户ID。

示例:如果admin的用户标识为3,用户名为username:joe@harry.com的用户标识为:56,则使用上面的代码,WebSecurity.CurrentUserId的输出将变为56.

答案 1 :(得分:1)

FormsAuthentication.SetAuthCookie(string, bool);可用于登录/注销特定用户,其中字符串为username,bool值为true / false,用于登录/注销。

FormsAuthentication.SetAuthCookie("user", true);将登录用户,WebSecurity将拥有其用户ID。

FormsAuthentication.SetAuthCookie("admin", false);将注销admin并将从WebSecurity中删除其userID。

相关问题