When the user logs in, I want to store his userID in the session with
HttpContext.Current.Session["UserID"] = 2354; (this is just a hard-coded example)
Then, when I run a page method, if I do
var test = HttpContext.Current.Session["UserID"];
will the variable test hold the value I stored when he logged in?
If this is a correct way of doing it, how do I access the session when I receive a call from a page method? I want to put the test =... line in a page method to identify which user the request is coming from.
Thanks.
The actual information for this session is stored on the server. So this is secure. The user can never change the value that has been stored on the server. The user cannot change his id if you stored this inside the session.
Once you query user from DB, you need to store user id in session session['user_id'] = user.id . Then when you need to access the user info, you retrieve user_id back from the session user_id = session['user_id'] and query the user back from DB, and use the model instance as you like.
No, it is not shared.
$_SESSION are super global variables which store values in SESSION and can be accessed like arrays. So user_id is just an index of a value in Session not a reserved keyword.
As has been already answered, yes - it should be fine, though if you sit on a page too long before calling a service using this method [WebMethod] it will fail. Best practice in that case is to check for the session and rebuild as necessary. The same is true for any other authentication to ensure that they haven't become unsyncronized or expired.
[WebMethod(EnableSession = true)]
HttpContext context = HttpContext.Current;
if (context.Session["UserID"] == null) {
Utilites.PopulateSessionVars(context.Request.ClientCertificate, context.Request.ServerVariables["REMOTE_ADDR"]);
}
String userId = context.Session["UserID"].ToString();
(where Utilities.PopulateSessionVars is a method to rebuild the session data off of whatever you're using to log in ... which in my case is a PKI certificate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With