In this tutorial you will learn how to store value in cookie and get cookie value in asp.net mvc application, working with cookie in asp.net mvc web application.
Cookies are one of the State Management techniques in Asp.net MVC, information we store in cookie for later use. Cookies are small files created in
There are two type of Cookies in Asp.Net :
To create cookie, we just need to create a new HttpCookie object in controller action
public ActionResult cookies() { // Create the cookie object. HttpCookie cookie = new HttpCookie("WTR"); cookie["website"] = "WebTrainingRoom"; // This cookie will remain for one month. cookie.Expires = DateTime.Now.AddMonths(1); // Add it to the current web response. Response.Cookies.Add(cookie); return View(); }
Just two simple things Request.Cookies (to retrive) and Response.Cookies (to add)
Here is how we can retrive Cookies information in in Asp.net MVC action
HttpCookie cookieObj = Request.Cookies["WTR"]; string _websiteValue = cookieObj["website"];
We all can retrieve all cookies in current httpContext, below code demonstrate how we can retrieve all values from cookie of current httpContext.
HttpCookieCollection _cookiees = HttpContext.Current.Request.Cookies; foreach (HttpCookie cookie in _cookiees) { // get the domain name who has set the cookie string _domainname = cookie.Domain; //retrive single value string _value = cookie.Value; // get multiple value from one cookie value NameValueCollection _values = cookie.Values; // get the date when expire DateTime _expirydate = cookie.Expires; }
For example, now you are accessing MakeMyTrip.Com then there may some cookies will be stored by some adverteiser.Com, then again when you visit a different site like GoIbibo.Com, some similar advertisement will be displayed to you using cookies was stored by adverteiser.Com earlier
So all advertisement you see while browsing your regular site like Google or Bing, are displayed based on some kind of third party cookies, that’s the reason you keep seeing similar type of advertisement when you keep checking different sites
So, you may have question like when to create a cookie in your web application and how!
When to create a cookie in your web application that will depend on type of application you have, if you have a mechanism like user login, and you want to provide functionality like “remember login” when user visit your site next time, you can create a persistent cookie on login button click
But if you want to create cookie when a user your visit your website, then use session start event in global.asax
You can write like this
private HttpCookie CreateStudentCookie() { HttpCookie wtrCookies = new HttpCookie("wtr"); wtrCookies.Value = "WebTrainingRoom"; wtrCookies.Expires = DateTime.Now.AddMonths(1); return wtrCookies; } protected void Session_Start(object sender, EventArgs e) { CreateStudentCookie(); }
Here we see another example of how use cookie for authentication.
First we store all user information in FormsAuthenticationTicket, then Encrypt all values into a string value, finally store that string into a cookie with FormsCookieName.
User user = new User(); user.id = 1001; user.username = "someUserName"; string _pipeSeparatedUserData = user.GetUserData(); DateTime expire = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(user.id, user.username, DateTime.Now, expire, false, _pipeSeparatedUserData); string hashTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); HttpContext.Current.Response.Cookies.Add(cookie);
Now we retrieve all values from cookie object and use for further authentication.
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket == null || authTicket.Expired) return ; string _name = authTicket.Name; string _userData = authTicket.UserData; }
In above example you can see how encrypted values stored in cookie and the retrieved values from cookie and decrypted for further use.