如何从 ASP.NET 中的任何类访问会话变量? [英] How to access session variables from any class in ASP.NET?
问题描述
我在应用程序的 App_Code 文件夹中创建了一个类文件.我有一个会话变量
I have created a class file in the App_Code folder in my application. I have a session variable
Session["loginId"]
我想在我的班级中访问这个会话变量,但是当我写下一行时,它给出了错误
I want to access this session variables in my class, but when I am writing the following line then it gives error
Session["loginId"]
谁能告诉我如何访问在 ASP.NET 2.0 (C#) 的 app_code 文件夹中创建的类中的会话变量
Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)
推荐答案
(已更新)
您可以使用 Session["loginId"]
从任何页面或控件访问会话变量,也可以使用 System.Web.HttpContext.Current.Session 从任何类(例如从类库内部)访问会话变量[登录ID"].
(Updated for completeness)
You can access session variables from any page or control using Session["loginId"]
and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].
但请继续阅读我的原始答案...
But please read on for my original answer...
我总是在 ASP.NET 会话周围使用包装类来简化对会话变量的访问:
I always use a wrapper class around the ASP.NET session to simplify access to session variables:
public class MySession
{
// private constructor
private MySession()
{
Property1 = "default value";
}
// Gets the current session.
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
// **** add your session properties here, e.g like this:
public string Property1 { get; set; }
public DateTime MyDate { get; set; }
public int LoginId { get; set; }
}
此类在 ASP.NET 会话中存储自身的一个实例,并允许您从任何类以类型安全的方式访问会话属性,例如:
This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:
int loginId = MySession.Current.LoginId;
string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;
DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;
这种方法有几个优点:
- 它使您免于大量的类型转换
- 您不必在整个应用程序中使用硬编码的会话密钥(例如 Session["loginId"]
- 您可以通过在 MySession 的属性上添加 XML 文档注释来记录会话项
- 您可以使用默认值初始化会话变量(例如,确保它们不为空)
这篇关于如何从 ASP.NET 中的任何类访问会话变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!