1. Cache:
Purpose: Temporary storage of data on the server or client to improve application performance by reducing the need to fetch data repeatedly.
Use Cases:
Static Data: Frequently used data like dropdown lists, menus, or data that doesn't change often.
Performance Optimization: Storing heavy computations or API responses temporarily to reduce load.
Example: Caching user profile pictures or frequently accessed pages.
Expiration: Cache typically has a set expiration time or can be invalidated manually.
ASP.NET Example:
Cache["UserDetails"] = userDetails; // Store data
var details = Cache["UserDetails"]; // Retrieve data
2. Cookie:
Purpose: Data stored on the client's browser, used to track or remember user preferences, sessions, or login state.
Use Cases:
Remember Me: Keeping users logged in even after the browser is closed.
Tracking: Storing user-specific preferences, like language settings.
Shopping Cart: Remembering items added to a cart for non-logged-in users.
Expiration: Can be set to persist (e.g., days, weeks) or deleted after the session ends.
Size Limit: Small size (~4KB per cookie).
ASP.NET Example:
// Set a cookie
HttpCookie cookie = new HttpCookie("UserName", "JohnDoe");
cookie.Expires = DateTime.Now.AddDays(7); // Optional expiration
Response.Cookies.Add(cookie);
// Get a cookie
var userName = Request.Cookies["UserName"]?.Value;
3. Session:
Purpose: Stores user-specific data on the server for the duration of a session (until the user closes the browser or the session times out).
Use Cases:
Temporary User Data: Storing data during a user's visit, like login credentials, user preferences, or cart items for logged-in users.
Sensitive Information: Since sessions are server-side, they are safer for storing sensitive data.
Complex Data: Larger or more complex data than cookies (like DataTables or lists).
Expiration: By default, sessions expire after 20 minutes of inactivity (configurable).
ASP.NET Example:
// Set a session
Session["UserName"] = "JohnDoe";
// Get a session
var userName = Session["UserName"]?.ToString();
Comparison Table
Kab Use Karein?
Cache:
Jab aapko performance optimize karni ho aur data frequently repeat hota ho.
Cookie:
Jab user preferences ya login ka "Remember Me" feature implement karna ho.
Session:
Jab sensitive ya complex data temporary store karna ho during a user's interaction.
How to use Cache, Cookie, or Session in webfrom, .net core razor / mvc?
1. Cache
ASP.NET Web Forms
Cache["UserDetails"] = userDetails; // Store data
var details = Cache["UserDetails"]; // Retrieve data
.NET Core (Middleware Cache)
.NET Core mein, built-in caching libraries jaise IMemoryCache aur IDistributedCache use hoti hain.
Example:
public class MyService
{
private readonly IMemoryCache _cache;
public MyService(IMemoryCache cache)
{
_cache = cache;
}
public void SetCacheData(string key, string value)
{
_cache.Set(key, value, TimeSpan.FromMinutes(10));
}
public string GetCacheData(string key)
{
return _cache.TryGetValue(key, out string value) ? value : null;
}
}
2. Cookie
ASP.NET Web Forms
HttpCookie cookie = new HttpCookie("UserName", "JohnDoe");
cookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie);
var userName = Request.Cookies["UserName"]?.Value;
.NET Core (Razor Pages/MVC)
.NET Core mein cookies set aur get karne ka syntax middleware-based hota hai.
Set Cookie:
Response.Cookies.Append("UserName", "JohnDoe", new CookieOptions
{
Expires = DateTimeOffset.Now.AddDays(7)
});
Get Cookie:
string userName = Request.Cookies["UserName"];
3. Session
ASP.NET Web Forms
Session["UserName"] = "JohnDoe"; // Set
var userName = Session["UserName"]?.ToString(); // Get
.NET Core (Razor Pages/MVC)
.NET Core mein sessions ke liye pehle middleware configure karna hota hai.
Startup.cs Configuration:
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
}
Set Session:
HttpContext.Session.SetString("UserName", "JohnDoe");
Get Session:
string userName = HttpContext.Session.GetString("UserName");
4. Differences Between Frameworks
Kya Same Hota Hai?
Concept: Cache, Cookie, aur Session ke concepts har jagah same hain.
Middleware: .NET Core aur APIs mein middleware ka setup zaruri hota hai.
Syntax: ASP.NET Web Forms ka syntax thoda different hota hai, lekin .NET Core aur MVC mein modern aur streamlined syntax hota hai.
Agar aap specific framework ke liye implementation chahte hain, to detail mein usi ke example provide kar sakta hoon.
![When and how to use Cache, Cookie, or Session ?](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTiP4ydrCPtEFC9G2IgXTONCeABBhPc5A3Hmy7zvkdUfxOlX9Gzrw_XaB3E_ZAPUpxNF6UP-4P24hozaNu_k2M0ApPNaOkC0OVu6ZSAxC3FGSIOhRHG5V_XmPheQQiDu1afEW9mQBh5BeK3cdZflMoYRtR3ZTBOkX2OJxwAXh1_eCF6jSoTISXvmaQ2mlk/s72-c/When%20and%20how%20to%20use%20Cache,%20Cookie,%20or%20Session.png)
No comments: