0

In my page I'm regenerating session id on every button click to go to the next page. I've already saved username in my session variable (session["uname"]=txtusername.text) in the time of log in. But as I'm regenerating new session id ,session["uname"] is having null reference because of new session id.That's why I want to set the session variable value using a Global.asax in session start function.

void Session_Start(object sender, EventArgs e) 
    {
       session["uname"]=here;
    }

But here in Global.asax page I'm unable access any value from my log in page.. The main problem is accessing any value in global.asax from code behind. How can I solve this......Plz help......Thanking in advance..............

Sudip Roy
  • 1
  • 2
  • You should take a look at storing your Page-level information some other way instead of accessing the control in Global.asax. Also, may I ask why you have to regenerate the Session ID everytime? – rikitikitik Jul 19 '12 at 05:48

2 Answers2

0
HttpContext.Current.Session["uname"]=here;
Amiram Korach
  • 13,056
  • 3
  • 28
  • 30
  • **thnks v much...bt main problem is of accessing any variable/control value from code behind to global.asax page..I'm unable to access textbox value from log in page or any variable in global.asax....** – Sudip Roy Jul 19 '12 at 05:39
0

First don`t write business logic in Global.asax . I want to point you out 3 basic things:

  1. When session_start() called
  2. How sessions are maintained
  3. Where you should set your session variables.

For the following details I am assuming you have login.aspx, login.aspx.cs:

As you know HTTP is stateless protocol, so every request is new request. So for every request session_start() will get executed.

When user request the resource for the first ever time, unique session will be generated, and cookie containing session Id will be sent to client.

For any further request from the user, HTTP client will pass the cookie to server, so user can be tracked by the server. This is how session works.


Now lets come to your code you are setting Session["uname"] in session_start() of Gloabl.asax, keep in mind that Globlax.asax is called before the page life-cycle begins so it does not have access to page data.

Instade you should set your Session["uname"] in login.aspx.cs file. Here check if users credentials are correct then:
set Session["uname"]=value.

Now for every other request Session["uname"] for that user will be available. And you can also retrieve/update the values at session_start() of Global.asax too.

  • Why should I use the constant session key "uname" on multiple levels? For example I can set or retrieve the current session locale via the `HttpContext.Current.ApplicationInstance` that I casted to my global.asax code behind class so I don't need to use a key like `"uname"` in my code. – djmj Aug 22 '12 at 14:02