且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据用户是否登录显示“登录”和“注销”链接?

更新时间:2023-12-04 19:34:34

我认为问题是在if条件下,你可以仔细检查。如果cookie值为null,我觉得这两个条件都不会满足。



Hi, I think the problem is here in the if condition, can you double check. I feel it both the conditions will not satisfy if the cookie vale is null.

protected void Page_Load(object sender, EventArgs e)
        {
            //checks if cookies exists, and if the login value is true
            //if it does exist and is true, it enables the logout button
            if (Request.Cookies["LoggedIn"] != null
                && Request.Cookies["LoggedIn"].Value == "true")
            {
                logoutLinkBtn.Visible = true;
                LoginLinkBtn.Visible = false;
            }
            else if (Request.Cookies["LoggedIn"] != null
                && Request.Cookies["LoggedIn"].Value == "false")
            {
                logoutLinkBtn.Visible = false;
                LoginLinkBtn.Visible = true;
            }
        }


谢谢,我查了一下,我用以下方式更改了我的代码:



Thank you, I checked it and i changed my code in the following way:

protected void Page_Load(object sender, EventArgs e)
        {
            //checks if cookies exists, and if the login value is true
            //if it does exist and is true, it enables the logout button
            if (Request.Cookies["LoggedIn"] != null
                && Request.Cookies["LoggedIn"].Value == "true")
            {
                logoutLinkBtn.Visible = true;
                
            }
            else if(Request.Cookies["LoggedIn"] == null || //if cookie does not exist
              (Request.Cookies["LoggedIn"] != null && //if cookie is valid
              Request.Cookies["LoggedIn"].Value != "true")) //but user is not logged in
            {
                LoginLinkBtn.Visible = true;
                logoutLinkBtn.Visible = false;
            }
        }





现在正在运作。



It is working now.


I认为使其不起作用的部分是您检查cookie对象是否为空的条件,如果它为空则应将其更改为null(如果未登录则启用注销按钮)



I think the part that's making it not to work is the condition where you checked if the cookie object is not null, you should change it to if it's null(for enabling the logout button if not signed in)

protected void Page_Load(object sender, EventArgs e)
        {
            //checks if cookies exists, and if the login value is true
            //if it does exist and is true, it enables the logout button
            if (Request.Cookies["LoggedIn"] != null
                && Request.Cookies["LoggedIn"].Value == "true")
            {
                logoutLinkBtn.Visible = true;
                LoginLinkBtn.Visible = false;
            }
            else if (Request.Cookies["LoggedIn"] == null
                && Request.Cookies["LoggedIn"].Value == "false")
            {
                logoutLinkBtn.Visible = false;
                LoginLinkBtn.Visible = true;
            }
        }