Static fields vs Session variables

前端 未结 4 2168
花落未央
花落未央 2020-12-05 02:24

So far I\'ve been using Session to pass some variables from one page to another. For instance user role. When a user logs in to the web application the role id of the user i

4条回答
  •  醉酒成梦
    2020-12-05 03:07

    No, using static variables for this is not the way to go:

    • If your AppDomain is recycled, all your static variables will be "reset"
    • Static variables don't scale horizontally - if you load-balance your application, a user who hits one server then a different one won't see the data store in the static variables in the first server
    • Most importantly, static variables will be shared by all access to that server... it won't be on a per-user basis at all... whereas from your description, you wouldn't want user X to see user Y's information.

    Fundamentally, you have two choices for propagating information around your application:

    • Keep it client-side, so each request gives the information from the previous steps. (This can become unwieldy with large amounts of information, but can be useful for simple cases.)
    • Keep it server-side, ideally in some persistent way (such as a database) with the client providing a session identifier.

    If you can use load-balancing to keep all users going to the same server, and if you don't mind sessions being lost when the AppDomain is recycled1 or a server going down, you can keep it in memory, keyed by session ID... but be careful.


    1 There may be mechanisms in ASP.NET to survive this, propagating session information from one AppDomain to another - I'm not sure

提交回复
热议问题