gpt4 book ai didi

c# - 只存在于当前执行页面的上下文中的静态变量?

转载 作者:行者123 更新时间:2023-11-30 21:12:50 24 4
gpt4 key购买 nike

按照我的网站设置方式,我有一个母版页、页面以及该页面内的控件,所有这些都可以显示有关查看用户的信息。

因为我多次需要此信息,所以我必须创建我的模型实例,然后在每次我需要从他们的帐户读取数据时返回用户对象。

为了解决这个问题,我做了以下事情:

public static class Core
{
private static PatientRow Patient;
public static PatientRow GetCurrentPatient()
{
if (Patient == null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.IsInRole("Patient"))
{
using (PatientModel model = new PatientModel())
{
Patient = model.Find<PatientRow>(User.CurrentUser.UserID);
}
}
return Patient;
}
}

如您所见,我正在检查私有(private)静态变量 Patient 是否为 null,如果是,则离开并获取它。下次我调用 GetCurrentPatient 时,因为 Patient 已经填充,我刚刚保存了自己的数据库调用等。

现在问题来了......众所周知,这意味着每次我调用 GetCurrentPatient 时,无论谁正在查看该站点,他们都将获得最后(或第一个)设置值。

我不想在 Session 中存储对象,这很麻烦,但我确实需要找到一种方法将静态范围限制在用户的 session 中,或者,一个合理的妥协,将其限制在当前页面的执行。

有什么建议吗?

干杯

编辑:在阅读 Darin 的回答之前,我已经实现了以下内容。

我拥有的每个 Page 都继承了一个 BasePage 类(以便更轻松地处理菜单等)。由于此处存储的任何代码仅在执行期间可用(静态变量除外),我只是创建了一个注册表字典集合,然后从我的原始 GetCurrentPatient 中,我只是检查注册表是否包含该对象,如果是,则返回它,如果没有得到它,存储它,最后返回它。

我将更改我当前的代码以匹配 Darin 的代码。非常感谢达林!

最佳答案

您可以将其存储在 HttpContext.Current.Items 包中。它将在 HTTP 请求的整个执行过程中可用,并且显然仅限于当前用户。因此,如果您在同一个请求中从多个位置多次调用 GetCurrentPatient 方法,它只会访问数据库一次。如果您需要为多个请求保留此信息,则需要使用 Session。

例如:

public static class Core
{
public static PatientRow GetCurrentPatient()
{
var patient = HttpContext.Current.Items["patient"];
if (patient == null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.IsInRole("Patient"))
{
using (PatientModel model = new PatientModel())
{
patient = model.Find<PatientRow>(User.CurrentUser.UserID);
HttpContext.Current.Items["patient"] = patient;
}
}
return patient;
}
}

不要在静态字段中存储任何内容,尤其是当此信息仅与当前用户相关时。

关于c# - 只存在于当前执行页面的上下文中的静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7213005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com