2014年7月15日 星期二

取得現在登入者的USERID,USERNAME,角色

http://social.msdn.microsoft.com/Forums/zh-TW/0d15269a-7e80-4038-b943-aa51f6714cb6/useridusername?forum=236

方法1:  session
程式碼區塊
login.aspx.cs
    protected void Login1_LoggedIn(object sender, EventArgs e)
    {
         Session["UserID"] = Login1.UserName;
    }



程式碼區塊
default.aspx.cs
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((string)Session["UserID"] != null)
        {
            string LgnName = (string)Session["UserID"];
            if (Roles.IsUserInRole(LgnName, "Boss"))
                Literal1.Text = "hi,Boss";
            else if (Roles.IsUserInRole(LgnName, "Manager"))
                Literal1.Text = "hi,Manager";
            else Literal1.Text = "hi~";
        }

方法2:COOKIE
程式碼區塊
login.aspx.cs   
 protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        //cookie
         DateTime now = DateTime.Now;
         HttpCookie MyCookie = new HttpCookie("UserName");
         MyCookie.Value = Login1.UserName;
         MyCookie.Expires = now.AddHours(1);//Cookie的到期
         Response.Cookies.Add(MyCookie);
    }
 程式碼區塊
default.aspx.cs   
protected void Page_Load(object sender, EventArgs e)
    {
        //cookie
        if (Request.Cookies.Get("UserID") != null)
        {
            HttpCookie MyCookie = Request.Cookies.Get("UserID");
            Literal1.Text = "MyCookie=" + MyCookie.Value;
        }
    }

沒有留言: