Сохранение / Загрузка OrderedDictionary в сеанс

#c# #.net #asp.net #session #ordereddictionary

#c# #.net #asp.net #сеанс #упорядоченный справочник

Вопрос:

Я пытаюсь сохранить OrderedDictionary в сеанс и перезагрузить его. по сути, это список игр «Last Played».

по какой-то причине словарь полностью НОВЫЙ …. кто-нибудь может точно определить причину?

 <%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IReadOnlySessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = null;

        if (context.Session["LastPlayed"] != null)
        {
            // Load Dictionary from Session
            GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];
            context.Response.Write("Loaded from Session");
        }
        else
        {
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();
            context.Response.Write("Created New Dictionary");
        }

        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }       
    }

}
  

Комментарии:

1. Код кажется прекрасным и отлично работает для меня на стандартной веб-странице. У меня это работает, потому что я использую объект сеанса страницы. Откуда берется ваша переменная context и как она передается / объявляется?

2. Верно, я тоже это тестировал, и результат был таким, как ожидалось. Я думаю, что ваш контекст передан неправильно.

3. Пожалуйста, просмотрите отредактированный пример кода.

Ответ №1:

Хорошо, итак, я нашел проблему, я использовал IReadOnlySessionState вместо IRequiresSessionState

 <%@ WebHandler Language="C#" Class="LastPlayed" %>

using System;
using System.Web;
using System.Web.SessionState;

public class LastPlayed : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        string GameTitle = context.Request["gt"];
        string GameAlias = context.Request["ga"];

        System.Collections.Specialized.OrderedDictionary GamesDictionary = (System.Collections.Specialized.OrderedDictionary)context.Session["LastPlayed"];

        if (context.Session["LastPlayed"] == null)
            // Creates and initializes a OrderedDictionary.
            GamesDictionary = new System.Collections.Specialized.OrderedDictionary();       
        try
        {
            if (GamesDictionary.Count >= 5)
                // Remove the last entry from the OrderedDictionary
                GamesDictionary.RemoveAt(GamesDictionary.Count - 1);
            // Insert a new key to the beginning of the OrderedDictionary
            GamesDictionary.Insert(0, GameTitle, GameAlias);
            context.Session["LastPlayed"] = GamesDictionary;
            context.Response.Write("Added");
        }
        catch { context.Response.Write("Duplicate Found."); }

    }

}
  

РЕДАКТИРОВАТЬ: Опубликован полный рабочий ответ

Комментарии:

1. 1, отлично замечено. Не знаю, можете ли вы / должны ли вы принять свой собственный ответ. Если вы не можете, может помочь добавить решение в исходное сообщение в качестве редактирования, чтобы сделать его более заметным?

2. я могу сделать это за два дня. только что опубликовал полный исправленный код с комментарием абатищева.

Ответ №2:

Избегайте двойного поиска в контейнере:

 var GamesDictionary = context.Session["LastPlayed"] as OrderedDictionary;
if (GamesDictionary != null)
{
    // do stuff
}
else
{
    // create new
    GamesDictionary = new OrderedDictionary();

    // probably! - put it inside
    context.Session["LastPlayed"] = GamesDictionary 
}
  

Комментарии:

1. Спасибо за это, постараюсь запомнить. 🙂