そもそもクラスをセッションに保存する必要があるかどうかは、まだ判断がつきません。私が質問したアプリでは、クラスをセッションに詰め込まないことを選択しました。実際には必要ありませんでした。怠け者でした。セッションを管理するこの方法を考え出すことは、常に価値がありました。これは、Web 開発でしばらくの間私を悩ませてきたものだからです。
私の研究から生まれたのは、セッション変数を管理するための静的クラスを作成することです。このクラスは、セッションへのすべての読み取りと書き込みを処理し、それらすべてを強く型付けして起動できるようにします。セッションのがらくたのためにあちこちで繰り返しコードを使用することは、常に私を悩ませてきました。タイプミスも少なくなります。
これで見つけたお気に入りの記事が 2 つあります。現在、そのうちの 1 つしか見つけることができず、見つけたらもう 1 つの記事を含める予定です。
1 つ目はCode Projectでした これは 2 つ目のリンク
かもしれません
パターンは簡単で簡単です。また、URL クエリ文字列からパラメーターを取得するためのリクエスト用のクラスも作成しました。クッキーにも拡張しない理由はありません。
これはパターンの最初の使用でした。文字列のみを使用したため、プライベート メソッドは少し制限されていますが、これは任意のクラスまたはプリミティブ型を使用するように簡単に変更できます。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
namespace BDZipper.Site
{
/// <summary>
/// This class maintains all session variables for us instead of handeling them
/// individually in the session. They are also strongly typed.
/// </summary>
public static class SessionManager
{
# region Private Constants
// Define string constant for each property. We use the constant to call the session variable
// easier not to make mistakes this way.
// I think for simplicity, we will use the same key string in the web.config AppSettings as
// we do for the session variable. This way we can use the same constant for both!
private const string startDirectory = "StartDirectory";
private const string currentDirectory = "CurrentDirectory";
# endregion
/// <summary>
/// The starting directory for the application
/// </summary>
public static string StartDirectory
{
get
{
return GetSessionValue(startDirectory, true);
}
//set
//{
// HttpContext.Current.Session[startDirectory] = value;
//}
}
public static string CurrentDirectory
{
get
{
return GetSessionValue(currentDirectory, false);
}
set
{
HttpContext.Current.Session[currentDirectory] = value;
}
}
//TODO: Update to use any class or type
/// <summary>
/// Handles routine of getting values out of session and or AppSettings
/// </summary>
/// <param name="SessionVar"></param>
/// <param name="IsAppSetting"></param>
/// <returns></returns>
private static string GetSessionValue(string SessionVar, bool IsAppSetting)
{
if (null != HttpContext.Current.Session[SessionVar])
return (string)HttpContext.Current.Session[SessionVar];
else if (IsAppSetting) // Session null with appSetting value
return ConfigurationManager.AppSettings[SessionVar];
else
return "";
}
}
}