如何使ASP.NET页面自定义类对象全局可访问且用户数据隔离?
问题
在ASP.NET项目的Default页面(default.cs)中,我定义了自定义类CLASSBenefitIncluded326,并声明了该类的静态对象Lawfirm1和Lawfirm2,代码如下:
namespace LawfirmsRewiever { public partial class Default : System.Web.UI.Page { public class CLASSBenefitIncluded326 { public string Begin { get; set; } public string End326 { get; set; } public string LOB { get; set; } public int id326 { get; set; } public CLASSBenefitIncluded326() { this.Begin = null; this.End326 = null; this.LOB = null; this.id326 = 0; } public CLASSBenefitIncluded326(string f, string l, string u, int a, string g, string j, string h, string Benefit326, string Medios326, string PrimerPago326) { this.Begin = f; this.End326 = l; this.LOB = u; this.id326 = a; } } public static CLASSBenefitIncluded326 Lawfirm1= new CLASSBenefitIncluded326(); public static CLASSBenefitIncluded326 Lawfirm2= new CLASSBenefitIncluded326(); } }
我希望这些对象能被页面的所有方法访问,同时确保多个用户同时使用应用时,各用户的对象属性内容彼此独立、不共享,请问如何简便实现这一需求?
解决方案
核心问题说明
你当前用static修饰的对象是应用域级别的共享资源,所有访问该网站的用户都会共用同一个Lawfirm1和Lawfirm2实例,这会导致用户之间的数据互相覆盖,完全不符合需求。
基础场景简便实现
直接去掉static修饰符,将对象改为页面的实例字段即可:
// 去掉static关键字,改为页面实例成员 public CLASSBenefitIncluded326 Lawfirm1 = new CLASSBenefitIncluded326(); public CLASSBenefitIncluded326 Lawfirm2 = new CLASSBenefitIncluded326();
可行性原因
- ASP.NET中,每个用户的页面请求都会创建一个独立的
Default页面实例,实例字段会随页面实例的创建而初始化,每个用户拥有专属的Lawfirm1和Lawfirm2对象,数据完全隔离。 - 页面内的所有方法(如事件处理方法、自定义方法)都可以直接访问这些实例字段,满足"页面所有方法可访问"的需求。
跨请求场景扩展
如果需要跨页面请求保留用户的这些数据(比如用户刷新页面后数据不丢失),可以把对象序列化后存入Session:
// 存储到Session Session["Lawfirm1"] = Lawfirm1; // 从Session读取 var lawfirm1 = Session["Lawfirm1"] as CLASSBenefitIncluded326;
注意:CLASSBenefitIncluded326类需要标记为可序列化(添加[Serializable]特性):
[Serializable] public class CLASSBenefitIncluded326 { // 原有属性和构造函数不变 }
内容的提问来源于stack exchange,提问作者Tempus Iruis
相关产品推荐
相关产品推荐

