开发者

How to add/remove/replace LIST in cookies using C#

How can add/remove/replace LIST in cookies using C#.

//Declaring the List for im开发者_运维知识库age list

List<string> imageList = new List<string>();
foreach (FeaturedPromo promo in base.FeaturedPromos)
{
    imageList.Add(promo.ImageHref);
}

In above code, I have got a list with all the Image HREF values in it, Now I want to add these values in cookies using C#, after that I can remove that item from cookies and also replace the value with other value of same item in cookies.

Please suggest!


Cookies are not removed they are just overwritten or expired (sometimes forced to expire).

To add it to cookies just create a Cookie Name Value collection and add each item from list to the Collection.

Example to add a list of items to cookies:

System.Collections.Specialized.NameValueCollection cookiecoll = new System.Collections.Specialized.NameValueCollection();
for(int i = 0 ; i < imageList.Length; i++)
{
    cookiecoll.Add("item_" + i,imageList[i] );
}

HttpCookie cookielist = new HttpCookie("MyListOfCookies");
cookielist.Values.Add(cookiecoll);
Response.Cookies.Add(cookielist);

Example To Edit "item_2"

 Response.Cookies["MyListofCookies"].Values["item_3"] = "new value";

Example to delete cookies:

Response.Cookies["MyListOfCookies"].Expires = DateTime.Now.AddDays(-1);

Example to delete a single item from list (just overwrite with nothing )

Response.Cookies["MyListOfCookies"].Values["item_3"] = String.Empty;


Note: But remember you can't add too much data in cookies.. many browsers have a upper limit to the size and number of cookies you can store.


you could use

// Add cookie
HttpContext.Current.Response.Cookies.Add(new HttpCookie("MyCookieBizkit", imageList));

// Remove cookie
HttpContext.Current.Response.Cookies.Remove("MyCookieBizkit");

// Edit
HttpContext.Current.Response.Cookies["MyCookieBizkit"] = imageList;

// Get
imageList = HttpContext.Current.Request.Cookies["MyCookieBizkit"] != null ? (List<string>)HttpContext.Current.Request.Cookies["MyCookieBizkit"] : new List<string>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜