Pergunta
I have a problem with my class below:
Iam tring to hold UserID without Session and of course Querystring, I thought i can store it in my UserClass.
So when i try to get the ID for example: Default.aspx:
MyUserClass userclass=new MyUserClass();//global
//(at button click)
userclass.GetUser(TextBox1.Text, TextBox2.Text);
int UserID=userclass.UserID;
when i reload the page UserID=0 that i get ok. then i tried to use a static variable for that. example:
static MyUserClass userclass=new MyUserClass(); //global
//(at button click)
userclass.GetUser(TextBox1.Text, TextBox2.Text);
int UserID=userclass.UserID;
i get the ID when i also reloaded the page, but when somebody else logins , my ID changes with the other ID
how can i do that with this way or i mean with properties?
The class is:
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;
}
}
Solução
The web is stateless by nature and as such each new request is "overwriting" the UserId value as it stands there is nothing to tie back the request back to your class. You need to use some sort of storage mechanism. As you've discounted using session and querystring I would suggest rolling your own lightweight ASP.NET membership provider and implementing IIdentity and IPrincipal and creating an Authentication Ticket (Cookie) through the provider in order to persist your post-login details (userId). Take a look at Brady Gasters blog and the comments posted there for how to do this.
http://www.bradygaster.com/custom-authentication-with-mvc-3.0
This post implements the membership in MVC 3 using Sessions however the comments and other links on the page show how to manipulate the code and use cookies auth. Implementing it in Web Forms (if youre using webforms) should also be fairly straightforward too.