zoukankan      html  css  js  c++  java
  • 非Page类使用session(Httpcontext.session和page.session区别)

    ASP.NET中Session高级使用技巧

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

    一、PAGE参数法:

    1、DLL中类的实现。
     

    [c-sharp] view plaincopy
    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中调用:

    [c-sharp] view plaincopy
    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。

    [c-sharp] view plaincopy
    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只读。

    [c-sharp] view plaincopy
      1. public class UseSession : System.Web.SessionState.IReadOnlySessionState  
      2. {  
      3.     static public int GetSessionCount()  
      4.     {  
      5.         return System.Web.HttpContext.Current.Session.Count;  
      6.     }  
  • 相关阅读:
    1509 加长棒
    51Nod 1158 全是1的最大子矩阵
    P2953 [USACO09OPEN]牛的数字游戏Cow Digit Game
    P3384 【模板】树链剖分
    北京集训DAY3
    北京集训DAY2
    北京集训DAY1
    51Nod 1422 沙拉酱前缀 二分查找
    51Nod 1109 01组成的N的倍数
    51Nod 1043 幸运号码 数位DP
  • 原文地址:https://www.cnblogs.com/mooncher/p/4103160.html
Copyright © 2011-2022 走看看