如何从会话对象读取值

本文关键字:读取 对象 会话 | 更新日期: 2023-09-27 18:31:46

在Linq中使用sql服务器存储过程,我将问题列表存储在会话对象中,如下所示。

DataClassesDataContext myContext = new DataClassesDataContext();
var QuestionList = myContext.sp_GetAllQuestions().ToList();
Session["QuestionsList"] = QuestionList;

如何从此会话对象读取或转换值,例如

var QuestionList= Session["QuestionsList"]

SQL 存储过程如下所示

SELECT top 24 ROW_NUMBER() OVER (ORDER BY QuestionID) AS QuestionNo,Q.QuestionID,Q.Question,Q.Choices,Q.CorrectAnswer,
 Q.RelatedInfo,Q.QuestionType,CS.Section FROM Questions Q left join dbo.ChapterSection CS on Q.SectionID=CS.SectionID

如何从会话对象读取值

我不喜欢每周类型化会话,因为每次使用都需要类型转换,所以我将所有类型/对象包装在强类型会话包装器中。

包装器底座:

public abstract class SessionBase<T> : SessionBase where T : new()
{
    private static readonly Object _padlock = new Object();
    private static string Key
    {
        get { return typeof(SessionBase<T>).FullName; }
    }
    public static T Current
    {
        get
        {
            var instance = HttpContext.Current.Session[Key] as T;
            if (instance == null)
            {
                lock (SessionBase<T>._padlock)
                {
                    if (instance == null)
                    {
                        HttpContext.Current.Session[Key] = instance = new T();
                    }
                }
            }
            return instance;
        }
    }
    public static void Clear()
    {
        var instance = HttpContext.Current.Session[Key] as T;
        if (instance != null)
        {
            lock (SessionBase<T>._padlock)
            {
                HttpContext.Current.Session[Key] = null;
            }
        }
    }
}

现在创建一个对象(将其标记为可序列化有帮助)

[Serializable]
public QuestionCollection
{
  public QuestionCollection()
  {
    this.Questions = new List<Question>();
  }
  public List<Question> Questions { get; set; }
}

现在使问题集合强类型问题集合会话

public QuestionCollectionSession : SessionBase<QuestionCollection>
{
}

现在你可以像这样使用它:

QuestionCollectionSession.Current.Questions.Add("Are you there?");

当您要从会话中清除/删除它时:

QuestionCollectionSession.Clear();

这就是使用var来推断类型的地方。

明确说明QuestionList的类型,如下所示:

List<sp_GetAllQuestionsResult> QuestionList = = myContext.sp_GetAllQuestions().ToList();
Session["QuestionsList"] = QuestionList;

现在,当您从需要将其转换为的值Session中获取值时,很明显,如下所示:

List<sp_GetAllQuestionsResult> QuestionList= Session["QuestionsList"] as List<sp_GetAllQuestionsResult>;
// Check if the list is null or not
if(QuestionList != null)
{
    // Safe to use list because it was found and successfully cast
}
List<Question> QuestionList= Session["QuestionsList"] as List<Question>;
List<Question> QuestionList= (List<Question>) Session["QuestionsList"];

您必须具有相同类型的对象才能强制转换,并且它必须是可序列化的。

如果第一个选项无法转换,则它将为您提供 null,第二个选项将崩溃。

实际上取决于您QuestionsList代表的类型,但是如果您假设QuestionListList<Question>那么您需要类似的东西:

var QuestionList= Session["QuestionsList"] as List<Question>;
News newsList=new News();
Session["news"]=newsList;

当您想要获取会话对象时;

News newList=Session["news"] as News;

你必须投射会话.像那样使用