如何从ASP.NET中的任何类访问会话变量? [英] How to access session variables from any class in ASP.NET?

查看:192
本文介绍了如何从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"]

谁能告诉我怎么这在APP_ code文件夹中创建ASP.NET 2.0中的一类内访问会话变量(C#)

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#)

推荐答案

(更新完整性)结果
您可以从任何页面访问会话变量或使用控制会话[登录ID] 并从任何类(例如,从一个类库中),使用 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;

该方法有几个优点:


  • 这样可以节省你很多的类型转换

  • 您不必在你的应用程序中使用硬codeD会话密钥(如会话[登录ID]

  • 您可以通过MySession的的属性
  • 添加XML文档注释记录您的会议项目
  • 您可以初始化使用默认值的会话变量(例如保证它们不为空)

  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

这篇关于如何从ASP.NET中的任何类访问会话变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆