简体   繁体   中英

How to print values of C# session object

I am saving some values in session as below.

List<MyEntity> MyVariable = <some values here>;
System.Web.HttpContext.Current.Session["MySession"] = MyVariable;

When I try to print MySession variable in Immediate Window then it displays following:

Count = 2
    [0]: {MyProject.Model.MyEntity}
    [1]: {MyProject.Model.MyEntity}

How do I print the values which are inside these indexes 0 and 1? I tried the following but it didn't work as it shows error "Cannot apply indexing with [] to an expression of type 'object'":

System.Web.HttpContext.Current.Session["MySession"][0];

You have to cast your value to the type you assigned, and apply the index on that :

((List<MyEntity>)System.Web.HttpContext.Current.Session["MySession"])[0];

The Session only hold the generic type Object for all values, you have to cast them to the correct type each time you access it. To avoid casting at multiple places, you can create a wrapper class around Session, as seen in this answer .

您必须将会话对象强制转换为列表,这是一个示例:

((List<MyEntity>)System.Web.HttpContext.Current.Session["MySession"])[0]

You could try this code:

using System.Web;

List<MyEntity> list = (List<MyEntity>)HttpContext.Current.Session["MySession"];

if (list != null)
{
    foreach (MyEntity item in list)
    {
        Response.Write(item.ToString());  // <-- you may want to override ToString to display the content
    }
}

You need to cast your session object, before you can access it as a list, because you can store all kind of object s in the session and by default an object has no indexer. Thence the error message.

After that you still somehow need to implement a way to display the content of the items. You could override the ToString method of your MyEntity class to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM