ASP.NET中Session高级使用技巧

在开发Aspx .NET软件时,有时需要把常用的东西封装到一个非PAGE类中,文章介绍在非Page类中使用Session的方法。

一、PAGE参数法:

1、DLL中类的实现。

  1. public class UserManager
  2. {
  3. private Page page;
  4. public UserManager(Page dd)
  5. {
  6. page=dd;
  7. }
  8. public string GetUser()
  9. {
  10. return page.Session["user"];
  11. }
  12. }

2、PAGE中调用:

  1. public class CheckPage : Page
  2. {
  3. public CheckPage()
  4. {
  5. UserManager um = new UserManager (this);
  6. string usr = um.GetUser();
  7. //具体处理
  8. }
  9. }

二、直接调用System.Web.HttpContext.Current.Session["key"]法。

如果在非Page类中直接使用System.Web.HttpContext.Current.Session["key"]肯定会抛出异常,因为
此时System.Web.HttpContext.Current.Session=null。一个类要访问Session,必须实现(或在基类已实
现)IRequireSessionState接口,这是一个标记接口,不需要实现任何函数,但你不用它标记一下你的类就肯定访问不了Session。

  1. public class UseSession : System.Web.SessionState.IRequiresSessionState    {
  2. static public int GetSessionCount()
  3. {
  4. return System.Web.HttpContext.Current.Session.Count;
  5. // 说明:如果不继承IRequiresSessionState接口的话,此时会抛出异常。
  6. }
  7. }

如果你只需要读Session,也可以用IReadonlySessionState接口,效果类似,不过是对Session只读。

    1. public class UseSession : System.Web.SessionState.IReadOnlySessionState
    2. {
    3. static public int GetSessionCount()
    4. {
    5. return System.Web.HttpContext.Current.Session.Count;
    6. }
    7. }
04-26 18:46
查看更多