ASP.NET C# Static Variables are global?

后端 未结 4 1428
执念已碎
执念已碎 2020-11-29 07:00

Today I released a small asp.net beta web application which allows internal staff to modify some product information. We started running into issues where users were overwri

相关标签:
4条回答
  • 2020-11-29 07:14

    You may want to take some time to familiarize yourself with what the static keyword is responsible for in C#. Read here: static in different languages and MSDN here.

    0 讨论(0)
  • 2020-11-29 07:20

    It's incorrect to say that a static variable exists application wide. They in fact exist at two different levels

    1. For non-generic types there is a single static variable per AppDomain
    2. For generic types there is one per generic instantiation per AppDomain

    An application can contain many AppDomains and is true in several types of applications.

    If you want to store user specific settings though, use a Session variable.

    0 讨论(0)
  • 2020-11-29 07:21

    Yes, in ASP.NET a static fields lifetime is for the app domain (note that this differs a bit for generic types).

    I'd recommend using the server Session for storage of data you want to associate with an instance of a client browser session (user login). i.e.

    Session["_groupID"] = Convert.ToInt16(Request.QueryString["GroupID"]);
    

    you can retrieve it by doing:

    short groupID = Convert.ToInt16(Session["_groupID"]);
    
    0 讨论(0)
  • 2020-11-29 07:25

    Static variables has the same lifetime as an application domain they were created in. So if you get some wrong values it can be some problems in the application logic or else. You should use SessionState for per-user data.

    0 讨论(0)
提交回复
热议问题