注销必须在asp.net中单击两次

时间:2011-10-02 00:37:48

标签: c# asp.net login

在我的母版页中,我有注销。单击“注销”按钮时,将执行以下代码

protected void singout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
            myCookie.Expires = DateTime.Now.AddDays(-1d);
            Response.Cookies.Add(myCookie);
            FormsAuthentication.SignOut();
            Response.Redirect("Home.aspx");
        }
    }

并且在同一主页中我的负载是

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
        }
    }
    private void LoadData()
    {
       Menu Items..
    }

当我点击注销时,菜单会在我基于角色的页面加载中消失,因此这意味着角色权限存储在会话中,因此它被清除但页面必须重定向到Home.aspx但它仍然存在在同一页面中,我必须再次单击退出以将页面重定向到home.aspx。我错了

2 个答案:

答案 0 :(得分:3)

只需使用FormsAuthentication而不触及代码中的Cookie,并且没有if语句,即可轻松进行注销操作。表单身份验证将自动为您处理cookie状态。

这也将解决双重注销的问题,因为您在第一次单击注销按钮时将用户重定向到受保护的页面。

protected void singout_Click(object sender, EventArgs e)
{
    Session.Abandon();
    //Removes the forms-authentication ticket from the browser:
    FormsAuthentication.SignOut(); 

    FormsAuthentication.RedirectToLoginPage();
    // ...or redirect the user to any place of choice outside the protected files. 

}

答案 1 :(得分:2)

尝试下面提到的代码。

protected void singout_Click(object sender, EventArgs e) 
    { 
        Session.Abandon(); 
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) 
        { 
            HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName); 
            myCookie.Expires = DateTime.Now.AddDays(-1d); 
            Response.Cookies.Add(myCookie); 
            FormsAuthentication.SignOut(); 
        }
        Response.Redirect("Home.aspx"); 
    } 
相关问题