Static fields vs Session variables

前端 未结 4 2169
花落未央
花落未央 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:04

    They are two very different things.

    • Session can be used out of process (important for load balancing)
    • Session can be more durable because of its out of process capabilities.
    • ASP.Net automatically manages Session concurrency.
    • Access to static variables needs to be manually synchronized.
    • Static is global to the entire app domain. If you set the value of a static field/property for one user, all users will get the same value. Not the desired behavior in your scenario.

    Any kind of data can be stored in Session. It then must be casted however.But static fields accept data with the correct datatype only.

    It's often helpful to abstract Session values with a helper class. This can improve testability and also allows you to strongly type properties and perform the cast in the internals of the class.

    Example:

    public List UserRoles
    {
        get
        {
            // optionally check that the value is indeed in session, otherwise this 
            // will throw
            return (List)Session["UserRoles"];
        }
    }
    

    See also:

    • C# Static variables - scope and persistence
    • does aspx provide special treatment for c# static variables

提交回复
热议问题