asp.net2.0 login控件登录后,判断用户是否在线.

来源:互联网 发布:保友电脑椅 知乎 编辑:程序博客网 时间:2024/06/04 17:46

很多人都是采取手写代码cookies或者session验证,我也在论坛里问了下,没有找到更好的答案.

仔细分析了一下,既然loginname和loginstatus都能简单判断用户是否登录,那么就应该能从这两个控件上来进行判断用户是否已经登录.

using System.Web.UI;
using System.Security.Principal;

protected void Page_Load(object sender, EventArgs e)
    {
       IPrincipal myPrincipal = this.User;
       if (myPrincipal.Identity.IsAuthenticated)
        {
            this.label1.Text = "没有用户登录";
        }
    }

myprincipal还有几个属性:

myprincipal.identity.name                           //用户名;

myprincipal.identity.isauthenticated         //是否已通过验证(登录);

myprincipal.identity.AuthenticationType  //验证类型;

 

网友给出一个更简单的方法:

不用using System.Security.Principal;

if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            //登陆
            userName = HttpContext.Current.User.Identity.Name;
        }
        else
        {
            //未登陆
        }

当然,username具备上面的几个属性.

 

或者直接用

if (User.Identity.IsAuthenticated)

  {
            //登陆
            userName = HttpContext.Current.User.Identity.Name;
        }
        else
        {
            //未登陆
        }

原创粉丝点击