非Page類使用session(Httpcontext.session和page.session區別)

來源:互聯網
上載者:User

標籤:blog   http   io   ar   使用   sp   strong   div   on   

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.     }  
    7. } 

非Page類使用session(Httpcontext.session和page.session區別)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.