What should I do if the current ASP.NET session is null? Ask Question

What should I do if the current ASP.NET session is null? Ask Question

In my web application, I do something like this to read the session variables:

if (HttpContext.Current.Session != null &&  HttpContext.Current.Session["MyVariable"] != null)
{
    string myVariable= (string)HttpContext.Current.Session["MyVariable"];
}

I understand why it's important to check why HttpContext.Current.Session["MyVariable"] is null (the variable might not have been stored in the Session yet or the Session has been reset for various reasons), but why do I need to check if HttpContext.Current.Session is null?

My understanding is that the session is created automatically by ASP.NET therefore HttpContext.Current.Session should never be null. Is this assumption correct? If it can be null, does it mean I should also check it before storing something in it:

if (HttpContext.Current.Session != null)
{
    HttpContext.Current.Session["MyVariable"]="Test";
}
else
{
    // What should be done in this case (if session is null)?
    // Is it possible to force the session to be created if it doesn't exist?
}

ベストアンサー1

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

コードがページ内にのみある場合は、この問題に遭遇することはありません。私の ASP .NET コードのほとんどは、null を繰り返しチェックせずに Session を使用しています。ただし、IHttpModule を開発している場合や、ASP .NET のより細かい詳細に取り組んでいる場合は、この点を考慮する必要があります。

編集

コメントへの回答: セッション状態が使用可能かどうかは、リクエストに対して AcquireRequestState イベントが実行されたかどうかによって決まります。ここで、セッション状態モジュールはセッション Cookie を読み取り、適切なセッション変数のセットを検索して作業を行います。

AcquireRequestState は、制御がページに渡される前に実行されます。したがって、ページから静的クラスを含む他の機能を呼び出している場合は、問題はありません。

たとえば、Application_Start イベントや静的コンストラクターを使用して、起動時に初期化ロジックを実行するクラスがある場合、セッション状態が利用できない可能性があります。結局のところ、現在の要求があり、AcquireRequestState が実行されているかどうかが問題となります。

また、クライアントが Cookie を無効にした場合、セッション オブジェクトは引き続き使用できますが、次のリクエストでは、ユーザーは新しい空のセッションを返します。これは、クライアントにセッション ステートバッグがまだない場合は、それが渡されるためです。クライアントがセッション Cookie を転送しない場合は、クライアントを同一として識別する方法がないため、新しいセッションが何度も渡されることになります。

おすすめ記事