Advertisement

Advertisement

When and how to use Cache, Cookie, or Session ?

When and how to use Cache, Cookie, or Session

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

Feature

Cache

Cookie

Session

Storage

Server-side

Client-side (browser)

Server-side

Lifetime

Until expired or invalidated

Configurable by expiration

Session duration (default: 20 mins)

Security

Medium (accessible to server)

Low (client-side storage)

High (server-side storage)

Size Limit

Large

~4KB per cookie

Larger data is supported

Use For

Performance optimization

Remembering user preferences

Temporary user data during session

Kab Use Karein?

  1. Cache:

    • Jab aapko performance optimize karni ho aur data frequently repeat hota ho.

  2. Cookie:

    • Jab user preferences ya login ka "Remember Me" feature implement karna ho.

  3. 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

Feature

ASP.NET Web Forms

Razor Pages/MVC (Core)

Web API

Cache

Cache class

IMemoryCache or IDistributedCache

Rarely used, but can configure IMemoryCache.

Cookie

HttpCookie

Response.Cookies.Append

Similar to Razor/MVC, used for authentication tokens.

Session

Session

HttpContext.Session

Not typically used in APIs. Stateless.


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 ?  When and how to use Cache, Cookie, or Session ? Reviewed by Rikesh on December 31, 2024 Rating: 5

No comments:

Powered by Blogger.