Login Session lost sometimes when redirect to acti

2019-04-16 21:30发布

问题:

While deploy an asp.net mvc 3 project, I got the issue recently which I have no idea why it happened.

I have a class named LoginSesion which will get the Authenticated User when user login and store in session.

public static LoginSession AuthenticatedUser
    {
        get
        {
            if (HttpContext.Current.Session["LoginSession"] != null)
                return HttpContext.Current.Session["LoginSession"] as LoginSession;
            return null;
        }
        set
        {
            HttpContext.Current.Session["LoginSession"] = value;
        }
    }

When I run the project, try to redirect user to a specific URL (e.g. http://localhost/user/details/1), the HttpContext.Current.Session["LoginSession"] come to Null and redirect user back to Login page.

The weird thing is this does not always null, just sometimes. And when server runs too slow, it happens too although the session has not expire yet.

I have set in the web.config the session timeout as follow:

<authentication mode="Forms">
  <forms loginUrl="~/UserProfiles/Logon" timeout="2880" />
</authentication>

and

<sessionState mode="InProc" timeout="2880" />

I'm using IIS 7.x for publishing and testing.

回答1:

You have to consider the following things:

1) The sessionState timeout is updated (restart from 0) every time a user calls a page. By contrast, the form timeout is updated every time a user calls a page AND at least half of the timeout (2880 in your case) is passed. That means, the two timeouts are not synchronized.

2) Pay attention to the Idle Time-out property in IIS application pool. It is about the time after which the application pool is recycled. That means that session variables are lost.



回答2:

That what you need - add this code to web.config/system.web:

<machineKey validationKey="C5034160419189092507195D247C6FCD9F54D7A967372A23078E09F6440087328A874AD69955F441B526A265CC3A17CDEAAE8AB21A16868F549C3077C39C8E9F" decryptionKey="078FAD13FAC4E41EB0762F0B34E3F4990A144897C3387A70A746187F3AECD8DE" validation="SHA1" decryption="AES" />   

    <sessionState timeout="300" mode="InProc"></sessionState>

this machinKey was generated from http://aspnetresources.com/tools/machineKey