0

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();

それはうまく実行され、セッションから値を取得しました。

4

2 に答える 2

1

Session ではなく Context を直接使用する必要があるのはなぜですか? コードから、セッションに値を設定し、ページの読み込み時に値を読み取るとしか想定できません。そのようなことをするのではなく、これを行うことができます:

  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();
    }
    

この助けを願っています..

于 2013-03-21T06:16:05.487 に答える
0

System.Web.HttpContext.Current.Session["myvariable"]両方の部分で使用

于 2013-03-21T06:15:49.100 に答える