这是获取 WebProfile 的正确方法吗?
-
02-07-2019 - |
题
我有一位用户报告说,当他们使用后退按钮返回网页时,他们会以不同的人的身份回来。他们似乎可能正在访问不同的用户个人资料。
以下是代码的重要部分:
//here's the code on the web page
public static WebProfile p = null;
protected void Page_Load(object sender, EventArgs e)
{
p = ProfileController.GetWebProfile();
if (!this.IsPostBack)
{
PopulateForm();
}
}
//here's the code in the "ProfileController" (probably misnamed)
public static WebProfile GetWebProfile()
{
//get shopperID from cookie
string mscsShopperID = GetShopperID();
string userName = new tpw.Shopper(Shopper.Columns.ShopperId, mscsShopperID).Email;
p = WebProfile.GetProfile(userName);
return p;
}
我正在使用静态方法和 static WebProfile
因为我需要在 a 中使用配置文件对象 static WebMethod
(阿贾克斯 pageMethod
).
- 这是否会导致配置文件对象被不同用户“共享”?
- 我没有正确使用静态方法和对象吗?
我改变的原因 WebProfile
反对 static
对象是因为我需要访问配置文件对象 [WebMethod]
(从页面上的 javascript 调用)。
- 有没有办法访问配置文件对象
[WebMethod]
? - 如果没有,我有什么选择?
解决方案
静态对象在应用程序的所有实例之间共享,因此如果您更改静态对象的值,则该更改将反映在访问该对象的应用程序的所有实例中。因此,如果您的网络配置文件被另一个线程重新分配(即在您为当前用户设置它之间,第二个用户访问页面),它将包含与您期望的不同的信息。
为了解决这个问题,您的代码应该类似于:
public WebProfile p = null;
protected void Page_Load(object sender, EventArgs e)
{
p = ProfileController.GetWebProfile();
if (!this.IsPostBack)
{
PopulateForm();
}
}
public static WebProfile GetWebProfile()
{
//get shopperID from cookie
string mscsShopperID = GetShopperID();
string userName = new tpw.Shopper(Shopper.Columns.ShopperId, mscsShopperID).Email;
return WebProfile.GetProfile(userName);
}
请注意,静态对象尚未设置,返回值应分配给调用方法中 Web 配置文件类的非静态实例。
另一种选择是在静态变量使用的整个过程中对其进行锁定,但这将导致性能严重下降,因为锁定将阻止对资源的任何其他请求,直到当前锁定线程完成 - 这对于网络应用程序。
其他提示
@杰里
如果用户的配置文件不经常更改,您可以选择将其存储在当前会话状态中。这将引入一些内存开销,但根据配置文件的大小和同时用户的数量,这很可能不是问题。你会做类似的事情:
public WebProfile p = null;
private readonly string Profile_Key = "CurrentUserProfile"; //Store this in a config or suchlike
protected void Page_Load(object sender, EventArgs e)
{
p = GetProfile();
if (!this.IsPostBack)
{
PopulateForm();
}
}
public static WebProfile GetWebProfile() {} // Unchanged
private WebProfile GetProfile()
{
if (Session[Profile_Key] == null)
{
WebProfile wp = ProfileController.GetWebProfile();
Session.Add(Profile_Key, wp);
}
else
return (WebProfile)Session[Profile_Key];
}
[WebMethod]
public MyWebMethod()
{
WebProfile wp = GetProfile();
// Do what you need to do with the profile here
}
这样,只要有必要,就可以从会话中检索配置文件状态,并且应该避免对静态变量的需要。
不隶属于 StackOverflow