这是获取WebProfile的正确方法吗?
时间:2020-03-06 14:40:47 来源:igfitidea点击:
我有一个用户报告说,当他们使用"后退"按钮返回到网页时,他们以另一个人的身份返回。他们似乎正在访问其他用户个人资料。
以下是代码的重要部分:
//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;
}
我使用的是静态方法和"静态WebProfile",因为我需要在"静态WebMethod"(ajax" pageMethod")中使用配置文件对象。
- 这会导致配置文件对象被不同的用户"共享"吗?
- 我不能正确使用静态方法和对象吗?
我将WebProfile对象更改为static对象的原因是因为我需要在WebMethod内访问配置文件对象。
- 有没有办法在[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配置文件类的NON STATIC实例。
另一个选择是在使用过程中始终锁定静态变量,但这会导致性能严重下降,因为该锁定将阻止对资源的任何其他请求,直到当前的锁定线程完成后才对网络不利。应用程序。
@杰瑞
如果配置文件对于用户而言并不经常更改,则可以选择将其存储在当前会话状态中。这将引入一些内存开销,但是取决于配置文件的大小和同时用户的数量,这很可能不是问题。我们将执行以下操作:
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
}
这样,只要有必要,就可以从会话中检索配置文件状态,并且应该避免使用静态变量。

