Introduction
In web applications, sometimes we need to store user information temporarily. For example:
ASP.NET MVC provides two common ways to store this information:
Many beginners get confused about when to use Session and when to use Cookies.
In this article, we will learn:
What is Session?
A Session stores user data on the server side.
When a user visits a website, the server creates a unique Session ID for that user. The session keeps user information during the browsing session.
Example:
If a user logs into a website, we can store the username in Session.
Session Example in ASP.NET MVC
Store Data in Session
public ActionResult Login()
{
Session["Username"] = "Abhay";
return View();
}
Retrieve Session Data
public ActionResult Dashboard()
{
string user = Session["Username"].ToString();
ViewBag.User = user;
return View();
}
Display Data in View
<h2>Welcome @ViewBag.User</h2>
What is this?
Output:
Welcome Abhay
Here the username is stored in the server session.
What are Cookies?
Cookies store user information in the user's browser.
Cookies remain stored even after the browser is closed (if expiry is set).
Example uses:
Remember login
Save language preference
Save theme settings
Cookies Example in ASP.NET MVC
Create Cookie
public ActionResult SetCookie()
{
HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = "Abhay";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
return View();
}
Read Cookie
public ActionResult GetCookie()
{
string name = Request.Cookies["UserName"].Value;
ViewBag.Name = name;
return View();
}
Display in View
<h2>User Name: @ViewBag.Name</h2>
What is this?
Output:
User Name: Abhay
Difference Between Session and Cookies
| Feature | Session | Cookies |
|---|
| Storage Location | Server | Browser |
| Security | More Secure | Less Secure |
| Data Size | Large Data | Small Data |
| Expiry | Ends when session ends | Can set expiry time |
| Access Speed | Slower | Faster |
When Should We Use Session?
Use Session when storing:
Login information
Shopping cart data
Temporary user data
Secure information
Because session data is stored on the server, it is more secure.
When Should We Use Cookies?
Use Cookies when storing:
Website preferences
Language settings
Remember me login
Theme settings
Cookies are useful when we want data to persist even after the browser closes.
Real-World Example
Imagine a shopping website.
Session stores:
Products added to cart
User login information
Cookies store:
This combination improves the user experience.
Common Beginner Mistake
Some beginners store sensitive data like passwords in cookies.
This is not recommended because cookies are stored in the browser and can be accessed easily.
Always store sensitive data in Session or database.
Conclusion
Session and Cookies are important features in ASP.NET MVC that help store user data during website usage.
In this article, we learned: