Reputation: 183
I would like to store the logged in users in my asp.net application to a collection and store this collection in application state. I have a login Page and on Default.aspx page load event i have the following code:-
protected void Page_Load(object sender, EventArgs e)
{
users = (List<Users>)HttpContext.Current.Application["loggedUsers"];
if (User.Identity.IsAuthenticated == false)
{
Server.Transfer("Login.aspx");
}
if (User.Identity.Name != "")
{
users.Add(new Users { userName = User.Identity.Name.ToString() });
HttpContext.Current.Application["loggedUsers"] = users;
}
}
However when running the application, after the login an exception of Object reference not set to an instance of an object is being thrown on the code where i'm adding new objects to the list. If i comment the following line:
users = (List<Users>)HttpContext.Current.Application["loggedUsers"];
The application would run accordingly, howevever if let's say we have two users, USER A and USER B, and USER A logs in, he is added to list, however as soon as USER B logs it will overwrite USER A.
In my webservice i have the following method which will then return the list of currently logged users which works fine.
[WebMethod(EnableSession = true)]
public List<Users> getLoggedInUsername()
{
return (List<Users>)Application["loggedUsers"];
}
Upvotes: 0
Views: 941
Reputation: 4550
The problem is that when your first user is entering you have no value in the application with loggedUser key . It should be a common practice to check for NULL before casting it.
List<User> user = null;
if(HttpContext.Current.Application["loggedUsers"] == null)
{
user = new List<User>();
}
else
{
user = (List<User>)HttpContext.Current.Application["loggedUsers"];
}
Upvotes: 2