Alternative to Session

1

I am using Session to store the company object that the user is logged in.

I also use to make filters, so he can only see what is the company's login.

However, I have the following problems:

1 - If the user has closed the tab, his authentication cookie is still in the machine, then when he accesses again, the Session is null, causing an error.

2- It's a multi tenant app, so if you have 1000 user logged in, there will be 1000 pointers in memory to store that Session

    
asked by anonymous 26.11.2014 / 12:40

2 answers

3

I totally disallow the use of Session in MVC , especially in applications that use Load-Balance: Use cookies ! The Http as well as the MVC is StateLess .

You do not even need to create memory pointers or make requests at the bank to find out who is logged in. Using cookies you must record just what is needed to identify the logged in user: Name, Id, Login, Enrollment, Company, etc. and encrypt this information before writing the cookie. Encapsulate everything in a class and persist it in the cookie.

Faster, safer, less network traffic and memory consumption and still in accordance with MS's own recommendations, so much so that Asp.NET Identity itself uses cookies in their endorsements and nothing Session.

Check how Identity behaves and do the same. It is very effective, test and tell me if it worked for you.

    
06.01.2015 / 20:14
2

I also use Session in my application to keep user access data. I consider it faster than looking through the direct database.

Question 1

Regarding the loss of the Session, I believe you should set your session time-out to a greater value. Change your Web.config as shown below:

<system.web>
  <sessionState timeout="60"></sessionState>
  ...

Another thing I do is in Global.asax.cs, I see if the session has already died and has Form authentication, I re-create the session. Example below:

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{            
    if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
    {                
        HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authenticationCookie != null)
        {
            FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(authenticationCookie.Value);
            if (!authenticationTicket.Expired)
            {
                if (Session["usuarioLogado"] == null)
                {
                    CriaNovamenteSession(authenticationTicket.Name);
                }
            }
        }
        else
            Session["usuarioLogado"] = null;
    }
}

Question 2

I have not tested with so many users, but I think it's better to have 1000 pointers than all the time to access the database to grab data.

    
26.11.2014 / 12:53