Cookies In ASP.NET MVC – Difference B/W Cookies & Sessions

What Is State Management ?

  • Web pages use HTTP protocol to communicate between a Web browser and a Webserver.
  • HTTP is a stateless protocol and cannot automatically indicate whether the sequential requests are coming from the same or different clients.
  • You can implement state management in an ASP.NET MVC application using one of the following options:
    • Cookies
    • TempData
    • Application State
    • Session State

What Are Cookies In ASP.NET MVC ?

  • Cookies are one of the State Management techniques, so that we can store information for later use. Cookies are small files that are created in the web browser’s memory (if they’re temporary) or on the client’s hard drive (if they’re permanent).
  • Cookies are used to store small pieces of information related to a user’s computer, such as its IP address, browser type, operating system, and Web pages last visited.
  • The purpose of storing this information is to offer a personalized experience to the user.
  • Cookies are sent to a client computer along with the page output.
  • These cookies are stored on the client’s computer.
  • When a browser requests the same page the next time, it sends the cookie along with the request information.
  • The Web server reads the cookie and extracts its value.
  • It then, process the Web page according to the information contained in the cookie and renders it on the Web browser.

Following figure shows how cookies are transmitted between browser and application:

There are two types of cookies:

  • The first one is the session cookies that are stored in the browser’s memory that are transmitted through the header during every request.
  • The other type of cookie is the persistent cookies that are stored in text files on a user’s computer. This type of cookie is useful when you need to store information for a longtime

There are two types of cookies:

  1. SESSION OR NON-PERSISTENT COOKIE. (TEMPORARY)
  2. PERSISTENT COOKIE (PERMANENT)
  • The first one is the session cookies that are stored in the browser’s memory that are transmitted through the header during every request.
  • Session cookies are temporary cookies and remain saved for current session only.
  • The other type of cookie is the persistent cookies that are stored in text files on a user’s computer. This type of cookie is useful when you need to store information for a longtime.
  • Persistent cookies are created for the duration, which is set in the cookie file.

Difference Between Cookies And Session

COOKIESSESSIONS
Cookies are used for client side state management.Sessions are used for server side state management.
It means cookies are stored in the client machine browser.It means sessions are stored in the server machine.
using CookiesDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CookiesDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(User u)
        {
            if(ModelState.IsValid == true)
            {
                HttpCookie cookie = new HttpCookie("Username");
                cookie.Value = u.Username;

                HttpContext.Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddDays(2);
                return RedirectToAction("Index","Dashboard");
            }
            return View();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CookiesDemo.Controllers
{
    public class DashboardController : Controller
    {
        // GET: Dashboard
        public ActionResult Index()
        {
            HttpCookie cookie = Request.Cookies["Username"];
            if(cookie != null)
            {
                ViewBag.Message = Request.Cookies["Username"].Value.ToString();
            }
            else
            {
                return RedirectToAction("Index","Home");
            }
            return View();
        }
    }
}

HomeController’s Index View – Source Code

@model CookiesDemo.Models.User

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("Index","Home",FormMethod.Post))
{
    <table>
        <tr>
            <td>
                @Html.LabelFor(model => model.Username)
            </td>
            <td>
                @Html.TextBoxFor(model => model.Username, new { @class = "form-control"})
                @Html.ValidationMessageFor(model => model.Username,"", new { @class = "text-danger" })
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" value="Submit" class="btn btn-info" />
            </td>
        </tr>
    </table>
}

DashboardController’s Index View – Source Code


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<h3>Welcome @ViewBag.Message</h3>

Model Class User – Source Code

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace CookiesDemo.Models
{
    public class User
    {
        [Required(ErrorMessage = "Username is required")]
        public string Username { get; set; }
    }
}

https://www.mediafire.com/file/t8f5c12jiqky2pe/COOKIES+IN+MVC.docx/file

https://www.mediafire.com/file/c1d8glhxv25y7x3/CookiesDemo.rar/file

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *