如何在ashx頁面獲取Session值(未將對象引用設置到對象的實例)

在一般事務處理頁面,可以輕鬆的得到 Request,Response對象,從而進行相應的操作,如下:

HttpRequest Request = context.Request;

HttpResponse Response = context.Response;


但是要得到 Session的值就沒有那麼簡單了。比如你要在ashx得到保存在Session中的登錄帳號Session["userAccount"]

如果你只是context.Session["userAccount"]的話是會報 “未將對象引用設置到對象的實例”的異常

所以,如果要想取Session中的值 ,需要如下所示

1、引入 命名空間:

using System.Web.SessionState;

using System.Web.SessionState;

2、實現IRequiresSessionState接口,具體如下  

 

    /// <summary>
    /// $codebehindclassname$ 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class AddUserInfo : IHttpHandler,IRequiresSessionState //就是這樣顯示的實現一下,不用實現什麼方法
    {

        public void ProcessRequest(HttpContext context)
        {

      //這樣你就可以如下 操作了

                  if(context.Session["userAccount"] != null)

     {

       string account = context.Session["userAccount"].ToString();

     }

      //...繼續下面的代碼

    }

  }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章