簡體   English   中英

如何使用Azure Redis會話狀態提供程序在ASP.NET會話中存儲集合

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

我在ASP.NET MVC 5應用程序中使用Microsoft.Web.Redis.RedisSessionStateProvider和Azure上配置的Redis緩存。

我說的是在控制器中定義的某些操作中將值存儲在Session中。 如果我存儲原始值( Session["Foo"]="Bar" )或原始集,則可以正常工作:

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

但是,如果我嘗試存儲自己的類的集合,則該集合不會持續存在(在另一個請求之后, Session["Products"]null ):

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

Product看起來像這樣:

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; }
}

我應該怎么做才能在會話中存儲此類的實例?

由於Redis是鍵值存儲,因此您的對象需要序列化為byte[]流。 嘗試使用[Serializable]屬性裝飾您的Product類。

參見MSDN

@lort,我認為您可能會遇到以下問題。 使用Redis會話狀態提供程序時,Redis中的會話字典本身就是一個哈希,其中每個會話鍵值對都是一個哈希字段/值對,據我所知,只能將字符串作為值,而不能將諸如列表之類的對象作為對象 正如@ haim770指出的那樣,您可以將列表轉換為JSON或XML之類的內容,並將該JSON / XML作為字符串編寫。 當您要使用Session變量(該列表)時,請將JSON / XML字符串值轉換回list。

. 例如,請參閱下文。我正在使用Microsoft Redis會話狀態提供程序

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;

在redis-cli窗口中,我可以看到顯示的產品列表的會話值。 請注意,會話字典是Redis哈希,每個“條目”是一個哈希字段。

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"

希望這個問題(OP或其他人)有所幫助,盡管問題仍然存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM