我使用aspx webforms和AJAX调用的组合。我想在c#端存储变量,这些变量使用ajax来回传递(然后最终在注销之前将这些变量保存到SQL数据库)。
我看到过类似的问题,但我仍然不确定
下面是我的一些javascript文件的样子:
$.ajax({
type: "POST",
url: "Index.aspx/DoStuff",
data: JSON.stringify({ 'someVariable': varStr }),
...
});
我的Index.aspx.cs
的主要结构如下:
static SomeCollection g_Collection;
protected void Page_Load(object sender, EventArgs e)
{
g_Collection = new SomeCollection();
}
[WebMethod]
public static string DoStuff(string someVariable)
{
g_Collection.Add(someVariable);
}
// At some point ajax also calls another method that saves
// the g_Collection to a database *for that user* (important)
// - based on their GUID
对于单个用户,一切都很好,然而,当多个用户登录时,g_Collection
被保存为单个使用的变量(如预期的那样,因为g_Collection
变量是static
)。如果2个登录用户调用DoStuff()
,他们将添加到同一个g_Collection
实例。
因为方法DoStuff()
是static
,所以我也将g_Collection
声明为static
。
如何创建g_Collection
的实例?
我需要声明什么(在Page_Load()
内?),以便g_Collection是一个登录用户的实例,同时在我的static
[WebMethod]
方法中仍然保持相同的功能?
我不知道为什么要在这种情况下使用静态成员。
- 如果你想要一个每个用户的集合,你可能应该简单地使用一个Session对象。
- 如果你想要一个全局集合(1代表所有用户),一个Application对象。