簡體   English   中英

在C#中訪問上下文會話變量

[英]Accessing context session variables in c#

我有一個擴展IHttpModule的ASP.NET應用程序和dll。 我已經使用以下方法通過以下方式將會話變量保存在httpcontext中:

public class Handler : IHttpModule,IRequiresSessionState
  {

 public void Init(HttpApplication httpApp)
 {
    httpApp.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}

 public void PreRequestHandlerExecute(object sender, EventArgs e)
        {
                var context = ((HttpApplication)sender).Context;
                context.Session["myvariable"] = "Gowtham";
        }
}

在我的asp.net Default.aspx頁面中,我使用了代碼來檢索值

   public partial class _Default : System.Web.UI.Page, IRequiresSessionState
    {
    protected void Page_Load(object sender, EventArgs e)
        {
      String token = Context.Session["myvariable"].ToString();
    }
}

我收到錯誤回應

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

為了確保變量是否存儲在會話中,我將值存儲在會話中后,通過以下方法在類處理程序中進行了交叉檢查

  string ss = context.Session["myvariable"].ToString();

它執行得很好,並從會話中檢索了值。

為什么需要使用Context而不直接使用Session? 從代碼中,我只能假定您將在Session中設置一個值,然后在頁面加載時讀取該值。 您可以執行以下操作,而不是執行類似的操作:

  1. 添加一個全局應用程序類,右鍵單擊您的項目,單擊添加>新建項,選擇全局應用程序類,然后在該文件上插入以下代碼以初始化值

     protected void Session_Start(object sender, EventArgs e) { Session["myvariable"] = "Gowtham"; } 
  2. 在Page_Load上,您可以通過以下方式訪問:

     if ( Session["myvariable"] != null ) { String token = Context.Session["myvariable"].ToString(); } 

希望有幫助。

在兩個部分中都使用System.Web.HttpContext.Current.Session["myvariable"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM