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开发者_StackOverflow社区 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.
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)
Yes, that should work. However, session and forms authentication timeouts are on different timers and have different default timeouts so you cannot guarantee that value in session will be available for the time period during which the user is authenticated if you are using forms authentication.
This should do it
//Note: this code hasn't been tested. Correct me if I'm wrong
//To Set:
if (Session["UserId"] == null)
Session["UserId"] = "12345";
//To Get it:
if (Session["UserId"] != null)
MyObject.Id = Session["UsedId"].ToString();
Yes, but its advisable to do a test straight after your test
variable assignment to make sure that the UserID was set correctly before you try to use it.
EDIT
You could try:
var test;
if (HttpContext.Current.Session["UserID"] != null)
{
test = HttpContext.Current.Session["UserID"];
}
Global.asax runs at the application level. You want the user sessions which is a differet http context. Initialize the Session in the home/default login page instead.
精彩评论