[MVC3-Tutorial] Users being logged off/sessions lost.

Discussion in 'General troubleshooting' started by Sergio Tapia, Mar 16, 2012.

  1. Hi there, thought I would write this thread in order to help the many people I see face when using Winhost.

    Basically it comes down to this:

    The fix is very simple, although it took some hunting to figure it out. Hopefully this thread helps a lot of people some headaches.

    Although not necessary to follow along this tutorial, I recommend reading this article for a general overview.

    1. Create a support ticket to request an installation of the SQL Server Session database. Include the Database name in your message.


    2. Add the following to your web.config file. (Not the one in the Views folder, the one in the root folder)


    You'll want to use your SQL database name, users name, and password.

    Code:
    ...
    <system.web>
        <sessionState mode="SQLServer"
                            allowCustomSqlDatabase="true"                  
                            cookieless="false"
                            timeout="2880"
                            sqlConnectionString="data Source='tcp:s027.Winhost.com';database='DB_3347_mydb';user id='DB_23_my_user'; password='mypassword';" />
    3. Generate a machine key.


    Generate a machine key using this tool:
    http://aspnetresources.com/tools/machineKey

    4. Copy the machine key and place it in the web.config file (the one in the root folder). Also add trust level full.


    Code:
    <machineKey validationKey="D87832412312312312332EB48DC12091C2A671F2B6BFB733E5C50179A875EE03902E0127A46D38" 
                    decryptionKey="0769851231231231231239F7" 
                    validation="SHA1" 
                    decryption="AES" />    
        <trust level="Full"/>
    Those are all the steps you need to take for sessions to work even if the app pool is recycled! :) Your users won't be logged out anymore.

    Here are two code snippets showing how I log in my users, and how I check if a user is logged in. Just for illustrative purposes.

    User log in:

    Code:
    [HttpPost]
    public ActionResult Login(LogOnModel model)
    {
        using (EfAccountRepository accountRepository = new EfAccountRepository())
        {
            if (accountRepository.ValidateCredentials(model.Email, model.Password))
            {
                //THE IMPORTANT BIT IS THIS.
                FormsAuthentication.SetAuthCookie(model.Email, true);
                return RedirectToAction("Index", "Home");
            }    
        }
    
        ModelState.AddModelError("", "Your email or password is incorrect.");
        return View(model);
    }
    And if the users is logged in, here's how I check:

    Code:
    public static bool UserIsPartOfCompany(HttpContext context)
            {
                //I use the HttpContext object for all my shenanigans. :)
                if (!context.Request.IsAuthenticated)
                    return false;
    
                using (EfAccountRepository accountRepository = new EfAccountRepository())
                {
                    var loggedInUser = accountRepository.FindByEmail(context.User.Identity.Name);
                    string[] userRoles = accountRepository.GetRolesForUser(loggedInUser.AccountId);
    
                    return userRoles.Contains("Editor") || userRoles.Contains("Finance") || userRoles.Contains("Administrator");
                }            
            }

    I really hope this helps people and hopefully the mods can sticky this thread in order to save countless tickets and headaches from users.

    If you have any questions, please let me know.
     
    Last edited by a moderator: Oct 14, 2015
    ComputerMan likes this.
  2. So, what should users using sql CE do?

    The constant recycling is garbage IMO. I'm a single user on a site that nobody is using, and I'm getting recycled just clicking back and forth between pages inside the admin area of orchard.

    Logging into the admin area clicking a link and then being told I'm not logged in is frustrating.
     
  3. If you're on a Winhost Basic account and running Orchard, you will run into problems, even with no users. Orchard generally needs more server memory than a Basic plan provides.

    I would recommend the Ultimate plan for someone running any CMS such as Orchard, DNN, etc. They are what we charitably refer to as memory hogs.
     
    Last edited: Oct 14, 2015
  4. Hi
    I followed all this for asp.net WebForm = is all good.
    but when i use for asp.net mvc, it comes the error message :
    Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.


    Do i miss something for mvc2 ? do i need extra settings ?

    <sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="Data Source=tcp:s07.Winhost.com;Initial Catalog=[XXXX];User ID=[XXXXX];Password=[XXXXX];Integrated Security=False;" cookieless="false" timeout="60" />
    <trust level="Full" />
    <machineKey validationKey=[XXXX] decryptionKey=[XXXX] validation="SHA1" decryption="AES" />


    Thanks
     
    Last edited by a moderator: Oct 14, 2015
  5. Sorry, My bad !
    quote from other source :
    "Know that session state behaves differently when you're not using the default InProc (in memory of the server in process) than when you put it out of process (state manager or sql server)."

    I'm trying to put a custom class in session state without marked with the Serializable attribute. That's why it comes the error.
     
    Michael likes this.

Share This Page