Cookies in Asp.net MVC Example

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.

What is Cookie in Asp.net MVC

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

  • Web browser's memory (if they're temporary)
  • client's hard drive (if they're permanent)

There are two type of Cookies in Asp.Net :

  • Persistent Cookies: Persistent Cookies are Permanent Cookies stored as a text file in the hard disk of the computer.
    persistent cookie also known as tracking cookie, because while setting this type of cookies, you can set a very long expiry date like one year and more.
    For example when you use Gmail, and click on "remember me" checkbox, that time a cookie stored in your computer which is used next time again you access Gmail from same computer
  • Non-Persistent Cookies: Non-Persistent cookies are temporary. They are also called browser memory cookies and session-based cookies

Add Remove Cookies in Asp.net MVC

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();
         }
Properties in HttpCookies Class:
  • Name: Contains the name of the Key.
  • Domain: Using these properties we can set the domain of the cookie.
  • Expires: This property sets the Expiration time of the cookies.
  • HasKeys: If the cookies have a subkey then it returns True.
  • Value: Contains the value of the cookies.
  • Secured:If the cookies are to be passed in a secure connection then it only returns True.
  • Path: Contains the Virtual Path to be submitted with the Cookies.

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;
}

What are Third-party cookies?

Third party cookie means cookies being set by the different domain, than the current one shown in the address bar.

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

Cookies with real time example

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();
}

use Cookie for Authentication

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.


Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial