2012-08-16 89 views
0

我有一个问题,我下面的类:用户名物业

荫特林持有用户名没有会话,当然查询字符串的,我想我可以把它保存在我的UserClass的。

所以,当我试图让例如ID:Default.aspx的:

MyUserClass userclass=new MyUserClass();//global 

//(at button click) 
userclass.GetUser(TextBox1.Text, TextBox2.Text); 
int UserID=userclass.UserID; 

当我重新加载页面的用户ID = 0,我得到确定。那么我试图使用一个静态变量。例如:

static MyUserClass userclass=new MyUserClass(); //global 
//(at button click) 
    userclass.GetUser(TextBox1.Text, TextBox2.Text); 
    int UserID=userclass.UserID; 

我得到的ID时,我还重新加载页面,但是当别人登录,我与其他的ID变化

我怎么能做到这一点用这种方式我指的是与性能?

类是:

public class MyUserClass 
{ 
    private int _UserID; 
    public int UserID 
    { 
     get 
     { 
      return _UserID; 
     } 
    } 


    public int GetUser(string UserName, string Pass) 
    { 
     int UserID=0; 
     try 
     { 

      DB.conn.Close(); 

      SqlCommand command = new SqlCommand("pUserkontrol", DB.conn); 
      command.CommandType = CommandType.StoredProcedure; 
      command.Parameters.AddWithValue("@puserName", UserName); 
      command.Parameters.AddWithValue("@pPass", Pass); 
      DataTable dt = new DataTable(); 
      DB.conn.Open(); 
      SqlDataReader dr = command.ExecuteReader(); 

      dt.Load(dr); 
      DB.conn.Close(); 
      if (dt.Rows.Count < 1) 
      { 

      } 

      else 
      { 
       foreach (DataRow datarow in dt.Rows) 
       { 
        _UserID = Convert.ToInt32(datarow["UserID"]); 
        //UserID = _UserID; 



       } 

      } 
     } 
     catch (Exception ex) 
     { 



     } 



     return UserID; 


    } 
} 

回答

0

该网站本质上是无状态的,因此每个新的请求被“覆盖”用户ID值,因为它代表有什么绑回请求回你的类。你需要使用某种存储机制。正如你已经打折使用会话和查询字符串,我会建议滚动自己的轻量级ASP.NET成员资格提供程序,并实施IIdentity和IPrincipal并通过提供程序创建一个身份验证票证(Cookie),以保持您的登录后详细信息(userId)。看一下Brady Gasters的博客,并在那里发布关于如何做到这一点的评论。

http://www.bradygaster.com/custom-authentication-with-mvc-3.0

这个职位实现使用会话但页面显示的意见等环节如何操作的代码,并使用cookie身份验证在MVC 3成员。在Web Forms中实现它(如果你使用webforms)也应该相当简单。

+0

非常感谢你,我还不能投票,所以谢谢你,这就是我的答案 – zapper 2012-08-16 11:35:40

+0

没问题,如果你不能投票就接受这个答案 - 这会对它作出一点点滴答,并给我一些代表! ; O) – bUKaneer 2012-08-16 11:39:37