Introduction
When building web applications, we often need to store user information temporarily. For example:
Keeping a user logged in
Saving user preferences
Storing shopping cart items
Remembering user settings
In ASP.NET MVC, two common ways to store this information are Session and Cookies.
Many beginners get confused about when to use Session and when to use Cookies. In this article, we will explain the difference between them in simple words with examples.
What is Session?
A Session is used to store user data on the server side.
Each user visiting a website gets a unique session ID, which allows the server to identify that user.
Example
If a user logs into a website, we can store their username in a session.
Session Example in ASP.NET MVC
Controller code:
public ActionResult Login()
{
Session["Username"] = "Rahul";
return View();
}Explanation
Here we are storing Rahul in the session variable.
This value will remain available until:
User logs out
Session expires
Browser is closed (depending on configuration)
Retrieving Session Data
We can retrieve the stored value like this:
public ActionResult Dashboard()
{
string user = Session["Username"].ToString();
ViewBag.User = user;
return View();
}View (Dashboard.cshtml)
<h2>Welcome @ViewBag.User</h2>Output
Welcome RahulWhat are Cookies?
A Cookie is a small piece of data stored in the user's browser.
Unlike sessions, cookies are stored on the client side.
They can remain even after the browser is closed (if expiration is set).
Creating Cookies in ASP.NET MVC
Controller code:
public ActionResult CreateCookie()
{
HttpCookie cookie = new HttpCookie("Username");
cookie.Value = "Rahul";
cookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie);
return View();
}Explanation
Here we are creating a cookie named Username that will be stored in the browser for 7 days.
Reading Cookies
public ActionResult ReadCookie()
{
string user = Request.Cookies["Username"].Value;
ViewBag.User = user;
return View();
}View:
<h2>Welcome @ViewBag.User</h2>Output
Welcome Rahul
Join the conversation! Your thoughts help the community grow.