Cookies in Asp.net MVC 4.6 and Asp.net Core

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 core web application.

Note: This tutorial was originally written for how to work with cookie in asp.net mvc 4.6 framework, but in asp.net core, there is big changes in implementation of most of the component from earlier version, cookie in asp.net core work differently, I am updating this post with new information, rather than creating a new post for cookie in asp.net core, hope this will help both developers.

How Cookie works 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

Cookie in Asp.net Core

To use cookie in asp.net core application, we need to configure the middleware in our program file, for Persistent cookie, we have to set the folder name F:\myapp\f1\ where the cookie file to be created.

using Microsoft.AspNetCore.DataProtection;
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"F:\myapp\f1\"))
.SetApplicationName("SharedCookieWebTrainingRoom");
builder.Services.ConfigureApplicationCookie(options => {
        options.Cookie.Name = ".AspNet.SharedCookie";
    });

After doing the above configuration if you run your application, you see some file has been created in specified folder with encryption key (look like HeSe21CHbwiTBkYlGWjp4BFZ4TpIqwFEbASDba IIRvIto6TP6ASJMM316Ufy2Y3hiBJBvgKDJX/de/odE2eOvg==)

If we want to use the cookie for authentication, then add the following lines in configuration

builder.Services.AddAuthentication("Identity.Application")
.AddCookie("Identity.Application", options =>
    {
        options.Cookie.Name = ".AspNet.SharedCookie";
    });

To add cookie in http response context object

 HttpContext.Response.Cookies.Append(
                     "myCookieName", "myCookieValue",
                     new CookieOptions() { SameSite = SameSiteMode.Lax });

Learn more about cookie configuration in asp.net core.

Add Remove Cookie in Asp.net MVC 4.6

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.


 
Cookies in Asp.net MVC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial