'Throws exception when session of class getting null - c#
I have stored logged in user details when user login to the system. And I have reusing it on many pages of my application. But after idle time, when I'm using the application it throws an error like below. How can I solve this?
public class GlobalVariables
{
public string login_user_name = string.Empty;
public string login_user_id = string.Empty;
public string login_user_role = string.Empty;
}
<sessionState mode="InProc" regenerateExpiredSessionId="true" stateNetworkTimeout="30" sqlCommandTimeout="30" cookieless="false" timeout="30"/>
When login, storing the login details to the Session["objGlobalVariableClass"] as below :
GlobalVariables obj_GlobalVariables = new GlobalVariables();
obj_GlobalVariables.login_user_id = userID;
obj_GlobalVariables.login_user_name = user_name;
obj_GlobalVariables.login_user_role = login_user_role;//getting from database
Session["objGlobalVariableClass"] = obj_GlobalVariables;
On every other pages:
GlobalVariables obj_GlobalVariables;
protected void Page_Load(object sender, EventArgs e)
{
obj_GlobalVariables= (GlobalVariables)Session["objGlobalVariableClass"];
try
{
if (obj_erms_GlobalVariables == null)
{
string log_data = "GlobalVariable details are getting null \r\n";
Response.Redirect("Default.aspx");
}
}
catch (ThreadAbortException)
{
// possibly do something here
Thread.ResetAbort();
}
}
if(!IsPostBack)
{
lbl_username.Text = "Welcome " + obj_GlobalVariables.login_user_name;
}
But after idle time, system shows error when using this logged in user details. It' becomes null there. How can I redirect to login page if it gets null anywhere in the system?
Solution 1:[1]
On web.config, I added below lines of code.
<authentication mode="Forms">
<forms loginUrl="Default.aspx" requireSSL="true" timeout="30"/>
</authentication>
This will auto logout the page when session time out. And hence that error will not come up.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2431727 |

