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);                 
HttpContext.Response.Cookies.Add(cookie);
           

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);
  Response.Cookies.Add(c);
  }

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.Cookies.Add(cookie);
//HttpContext.Response.Cookies.Remove(“some_cookie_name”);
//HttpContext.Response.SetCookie(cookie);

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

http://stackoverflow.com/questions/19128507/using-cookie-in-asp-net-mvc-4

http://stackoverflow.com/questions/6797350/asp-net-mvc-cookie-implementation

Advertisements
Leave a comment

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: