简体   繁体   中英

Serialize, deserialize object from cookie in MVC application C#

I need to store an object list in a cookie. I know that I must serialize to store my list in cookie.

I tried to use JsonConvert for serialize and deserialize Object.

This line of code works ok.

Response.Cookies.Add(new HttpCookie("ShoppingCart", JsonConvert.SerializeObject(list)));

but when I try to get the cookie value

var shoppingList = HttpContext.Request.Cookies.Get("ShoppingCart");

I get the following exception:

An exception of type 'System.Web.HttpRequestValidationException' occurred in System.Web.dll but was not handled in user code

Can you please advise what I do wrong here. Thanks! Additional information: A potentially dangerous Request.Cookies value was detected from the client (

The default settings in several versions of MVC block requests with HTML or XML code in the POST/GET/COOKIE.

Usually people advice to change the validation settings, but since this is only about the content of a cookie, you are probably better off encoding the information: See this duplicate question

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