1

我有一个用户报告说,当他们使用后退按钮返回一个网页时,他们会以另一个人的身份返回。似乎他们可能正在访问不同的用户个人资料。

以下是代码的重要部分:

//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;
}

我使用静态方法和 astatic WebProfile因为我需要在static WebMethod(ajax pageMethod) 中使用配置文件对象。

  • 这会导致不同用户“共享”配置文件对象吗?
  • 我没有正确使用静态方法和对象吗?

我将WebProfile对象更改为static对象的原因是因为我需要访问 a 中的配置文件对象[WebMethod](从页面上的 javascript 调用)。

  • 有没有办法在 a 中访问配置文件对象[WebMethod]
  • 如果没有,我有什么选择?
4

2 回答 2

1

静态对象在应用程序的所有实例之间共享,因此如果您更改静态对象的值,该更改将反映在访问该对象的应用程序的所有实例中。因此,如果您的网络配置文件在您为当前用户设置它之间由另一个线程(即第二个用户访问页面)重新分配,它将包含与您预期不同的信息。

要解决此问题,您的代码应类似于:

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 实例。

另一种选择是在使用的整个过程中锁定静态变量,但这会导致性能严重下降,因为锁定会阻塞对资源的任何其他请求,直到当前锁定线程完成 - 这在网络应用程序。

于 2008-09-24T18:24:15.797 回答
1

@Geri

如果用户的配置文件不经常更改,您可以选择将其存储在当前会话状态中。这将引入一些内存开销,但取决于配置文件的大小和同时用户的数量,这很可能不是问题。你会做这样的事情:

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
}

以便在必要时从会话中检索配置文件状态,并且应该绕过对静态变量的需求。

于 2008-09-25T08:54:18.607 回答