简体   繁体   中英

How to store a collection in ASP.NET Session using Azure Redis Session State Provider

I am using Microsoft.Web.Redis.RedisSessionStateProvider with Redis Cache configured on Azure, in ASP.NET MVC 5 application.

And I'm talking about storing values in Session in some action defined in controller. It works fine if I store primitive values ( Session["Foo"]="Bar" ) or collection of primitives:

List<int> items = new List<int>();
items.Add(5);
Session["Items"] = items;

But if I try to store collection of my own class, it doesn't persist (after another request, Session["Products"] is null ):

List<Product> products = new List<Product>();
products.Add(db.Find(Id));
Session["Products"] = products;

Class Product looks like that:

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int CategoryID { get; set; }
    [ForeignKey("CategoryID")]
    public Category Category { get; set; }
    public decimal Price { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
}

What should I do to store instances of this class in session?

Since Redis is a Key-Value store, your objects need to be serialized to a byte[] stream. Try to decorate your Product class with the [Serializable] attribute.

See MSDN .

@lort, I think the problem you might be facing is the following. . As @haim770 pointed out, you can convert the list into something like JSON or XML and write that JSON/XML as a string. When you want to use the Session variable (that list), convert the JSON/XML string value back to list.

For example, see below.I am using Microsoft Redis Session State provider Microsoft.Web.Redis.RedisSessionStateProvider .

JavaScriptSerializer ser = new JavaScriptSerializer();
List<Product> products = new List<Product>();
products.Add(new Product{Name="test", Description="test"});
string productsField = ser.Serialize(products);
Session["Products"] = productsField;

In redis-cli window, I can see the session value for list of products displayed. Please note that the session dictionary is a Redis Hash and each "entry" is one Hash field.

redis 127.0.0.1:6379> hgetall /SessionInRedis_nnl24530afhndnchb2f3ronc_Data
1) "loginTime"
2) "\x00\x01\x00\x00\x00\xff\xff\xff\xff\x01\x00\x00\x00\x00\x00\x00\x00\x06\x01
\x00\x00\x00\x149/25/2014 7:52:03 PM\x0b"
3) "UserName"
4) "\x00\x01\x00\x00\x00\xff\xff\xff\xff\x01\x00\x00\x00\x00\x00\x00\x00\x06\x01
\x00\x00\x00\x06prasad\x0b"
5) "Products"
6) "\x00\x01\x00\x00\x00\xff\xff\xff\xff\x01\x00\x00\x00\x00\x00\x00\x00\x06\x01
\x00\x00\x00&[{\"Name\":\"test\",\"Description\":\"test\"}]\x0b"

Hope this helps (the OP or maybe someone else) although the question is old.

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