0

I am creating a login system and I want a way to sort of cache information without retrieving the same information from the database.

for example I would have a static class called tokenData. token data would be a private class to store login token, username, expireDate, etc. So every time I visit another page it would check the static class for the data. The token is then stored in session / cookie to produce the lookup. If the data is not in the token static class (e.g. application pool restart) then it would check the database for the record when the user logs in and creates another based on the data in the token table.

Can someone offer me any advice is this is acceptable practice or offer me anything to improve and issues that can arise?

an exmaple is

public class userToken
{
      private string name;
      private string tokenId;         

      private static List<userToken> userData = new List<userToken>();

      public void add(userToken);
      public userToken Find(string tokenId);
}
James Andrew Smith
  • 1,516
  • 2
  • 23
  • 43
  • I don't think you're using "static" correctly here. You may want to look into caching. – CodeCaster Sep 18 '14 at 12:42
  • Use reliable ORM like NHibernate - it has 2-level cache. Use cookies - and even better use authorization like ASP.Net identity which has this functionallity build-in. – fex Sep 18 '14 at 12:45
  • Use one of the [three built-in mechanisms for storing data across requests](http://stackoverflow.com/questions/5096544/application-vs-session-vs-cache). – D Stanley Sep 18 '14 at 12:46
  • Look at [this](http://stackoverflow.com/questions/8919095/lifetime-of-asp-net-static-variable), it can be useful. – sedovav Sep 18 '14 at 12:46

2 Answers2

1

Never ever ever use static for user or session specific data. static is shared across ALL sessions! You might end up with user sessions sharing confidential data.

Use HttpContext.Session or HttpContext.Cache.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

Your solution can introduce errors when run on more than a single server with a single user. The cache you are building is not thread safe. It will also introduce errors when your app is run across 2+ servers in a cluster (load balanced).

I would look into using a proper caching toolset (memcached, etc.)

Ken Brittain
  • 2,255
  • 17
  • 21