MVC C# Cookie management

Declare Object Class

public class LogedInInfo
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string ShopID { get; set; }
        public string ShopName { get; set; }
        public string CounterID { get; set; }

Assign object value and set Cookie

LogedInInfo info = new LogedInInfo(); // assign object to info
var json = JsonConvert.SerializeObject(info);
HttpCookie cookie = new HttpCookie("LogedInInfo", json);
cookie.Expires = DateTime.Now.AddDays(30);                 

Get cookie value from object

 private LogedInInfo GetLogedInInfo()
 LogedInInfo info= new LogedInInfo();
 if (HttpContext.Request.Cookies["LogedInInfo"] != null)
  HttpCookie cookie = HttpContext.Request.Cookies.Get("LogedInInfo");
  info = Newtonsoft.Json.JsonConvert.DeserializeObject(cookie.Value) as LogedInInfo;
    return info;

Clear Cookie/Remove Cookie

 if (Request.Cookies["LogedInInfo"] != null)
  var c = new HttpCookie("LogedInInfo");
  c.Expires = DateTime.Now.AddDays(-1);

Get Cookie in ASP.NET *.aspx.cs

LogedInInfo info = new LogedInInfo();
if (Request.Cookies["LogedInInfo"] != null)
var value = Request.Cookies["LogedInInfo"].Value;
info = Newtonsoft.Json.JsonConvert.DeserializeObject(value) as LogedInInfo;
return info;

Other userfull tricks


Response.SetCookie(cookie); //SetCookie is used for update the cookies.
Response.Cookie.Add(cookie); //This is used for Add cookies.

Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: