Localization and Session

Back

Loading concept...

🌍 ASP.NET Localization & Session State

Making Your App Speak Every Language (And Remember Who’s Visiting!)


The Magic Translation Box 📦

Imagine you have a magic box that can translate anything you say into any language in the world. You put in “Hello” and out comes “Hola” (Spanish), “Bonjour” (French), or “こんにちは” (Japanese)!

That’s exactly what Localization does in ASP.NET. Your app learns to speak different languages automatically!


🎯 What We’ll Learn

graph TD A["🌍 Localization"] --> B["📁 Resource Files"] A --> C["⚙️ Culture Configuration"] A --> D["🔍 Request Culture Providers"] E["💾 Session State"] --> F["Remember User Data"] style A fill:#667eea,color:#fff style E fill:#4ECDC4,color:#fff

1. 🌍 What is Localization?

The Story

Think of a tour guide at a famous museum. When visitors come:

  • 🇺🇸 American visitors? Guide speaks English
  • 🇫🇷 French visitors? Guide speaks French
  • 🇯🇵 Japanese visitors? Guide speaks Japanese

Localization makes your website work like this smart tour guide!

Simple Definition

Localization = Teaching your app to show the right language and format for each user

What Gets Localized?

Item Example
Text “Welcome” → “Bienvenido”
Dates 01/15/2024 → 15/01/2024
Numbers 1,000.50 → 1.000,50
Currency $100 → €100

Quick Example

// Enable localization services
builder.Services.AddLocalization(
    options => options
    .ResourcesPath = "Resources"
);

This tells ASP.NET: “Hey, look in the ‘Resources’ folder for translations!”


2. 📁 Resource Files

The Story

Imagine you have a filing cabinet with folders for each language:

  • 📂 English folder → Has all English words
  • 📂 Spanish folder → Has all Spanish words
  • 📂 French folder → Has all French words

When someone visits, you grab the right folder! That’s what Resource Files do.

What Are Resource Files?

Resource Files (.resx) = Special files that store translations for each language

File Naming Rules 📝

Messages.resx          ← Default (usually English)
Messages.es.resx       ← Spanish
Messages.fr.resx       ← French
Messages.de.resx       ← German
Messages.ja.resx       ← Japanese

The pattern is: FileName.{language-code}.resx

Inside a Resource File

Name (Key) Value
HelloMessage Hello, World!
WelcomeUser Welcome, {0}!
GoodbyeMessage Goodbye!

Using Resources in Code

// In your controller
public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController>
        _localizer;

    public HomeController(
        IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult Index()
    {
        // Gets "Hello" in user's language!
        var greeting = _localizer["HelloMessage"];
        return View();
    }
}

Using Resources in Razor Views

@inject IViewLocalizer Localizer

<h1>@Localizer["WelcomeTitle"]</h1>
<p>@Localizer["WelcomeMessage"]</p>

3. ⚙️ Culture Configuration

The Story

Think of culture like a costume. When you visit different countries:

  • 🎭 In USA: You wear “en-US” costume
  • 🎭 In Spain: You wear “es-ES” costume
  • 🎭 In Japan: You wear “ja-JP” costume

Each costume changes how dates, numbers, and text look!

What is Culture?

Culture = A set of rules for language + region (like “en-US” = English in USA)

Culture Codes Explained

Code Meaning
en English (general)
en-US English (USA)
en-GB English (UK)
es Spanish (general)
es-MX Spanish (Mexico)

Setting Up Supported Cultures

// In Program.cs
var supportedCultures = new[]
{
    "en-US", "es", "fr", "de", "ja"
};

builder.Services.Configure<RequestLocalizationOptions>(
    options =>
    {
        options.SetDefaultCulture("en-US");

        options.AddSupportedCultures(
            supportedCultures);

        options.AddSupportedUICultures(
            supportedCultures);
    });

Don’t Forget the Middleware!

// In Program.cs (after Build())
app.UseRequestLocalization();

This line is super important! Without it, nothing works.

Two Types of Culture

graph LR A["Culture"] --> B["CurrentCulture"] A --> C["CurrentUICulture"] B --> D["Formats dates &amp; numbers"] C --> E["Chooses which text to show"] style A fill:#667eea,color:#fff

4. 🔍 Request Culture Providers

The Story

Imagine a detective 🕵️ trying to figure out what language you speak. The detective has clues:

  1. First clue: Check the URL
  2. Second clue: Check your cookies
  3. Third clue: Check your browser settings

Request Culture Providers are these detectives!

What Are They?

Request Culture Providers = Different ways to detect which language a user wants

The Three Built-in Detectives

graph TD A["User Visits Site"] --> B["QueryStringProvider"] B -->|Not found| C["CookieProvider"] C -->|Not found| D["AcceptLanguageProvider"] D -->|Not found| E["Use Default Culture"] style A fill:#667eea,color:#fff

1️⃣ Query String Provider

Look at the URL for clues!

https://mysite.com/home?culture=es
https://mysite.com/home?ui-culture=fr

2️⃣ Cookie Provider

Check saved preferences!

// Save user's choice in a cookie
Response.Cookies.Append(
    CookieRequestCultureProvider
        .DefaultCookieName,
    CookieRequestCultureProvider
        .MakeCookieValue(
            new RequestCulture("es")),
    new CookieOptions
    {
        Expires = DateTimeOffset.Now.AddYears(1)
    }
);

3️⃣ Accept-Language Header Provider

Check browser settings automatically!

The browser sends: Accept-Language: es,en;q=0.9

This means: “I prefer Spanish, but English is okay too”

Customizing Provider Order

options.RequestCultureProviders = new List
    <IRequestCultureProvider>
{
    new QueryStringRequestCultureProvider(),
    new CookieRequestCultureProvider(),
    new AcceptLanguageHeaderRequestCultureProvider()
};

Creating a Custom Provider

public class RouteDataRequestCultureProvider
    : RequestCultureProvider
{
    public override Task<ProviderCultureResult?>
        DetermineProviderCultureResult(
            HttpContext httpContext)
    {
        var culture = httpContext
            .GetRouteValue("culture")?.ToString();

        if (string.IsNullOrEmpty(culture))
            return NullProviderCultureResult;

        return Task.FromResult(
            new ProviderCultureResult(culture));
    }
}

5. 💾 Session State

The Story

Imagine you’re at a coffee shop ☕. The barista remembers:

  • Your name
  • Your favorite drink
  • Your loyalty points

Every time you visit, they remember you! That’s Session State.

What is Session State?

Session State = A way to remember information about a user while they browse your site

How It Works

graph LR A["User Visits"] --> B["Server Creates Session"] B --> C["Gives User a Session ID"] C --> D["User Carries ID Like a Ticket"] D --> E["Server Remembers Everything"] style B fill:#667eea,color:#fff

Setting Up Session

// In Program.cs

// Step 1: Add session services
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout =
        TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

// Step 2: Use session middleware
app.UseSession();

Storing Data in Session

// Save a simple string
HttpContext.Session.SetString(
    "Username", "John");

// Save a number
HttpContext.Session.SetInt32(
    "CartItems", 5);

// Save complex objects (as JSON)
var user = new UserInfo
{
    Name = "John",
    Age = 25
};
HttpContext.Session.SetString(
    "UserInfo",
    JsonSerializer.Serialize(user));

Reading Data from Session

// Get a string
var username = HttpContext.Session
    .GetString("Username");

// Get a number
var cartItems = HttpContext.Session
    .GetInt32("CartItems");

// Get complex object
var userJson = HttpContext.Session
    .GetString("UserInfo");
if (userJson != null)
{
    var user = JsonSerializer
        .Deserialize<UserInfo>(userJson);
}

Session vs Cookies

Feature Session Cookies
Storage Server User’s Browser
Size Large (MB+) Small (4KB)
Security More Secure Less Secure
Expiry When idle or closed Set by you

Pro Tips 💡

// Always check if session has data!
if (HttpContext.Session
    .GetString("Username") != null)
{
    // User is logged in
}
else
{
    // User is a guest
}

🎯 Complete Setup Example

Here’s everything together!

// Program.cs
var builder = WebApplication
    .CreateBuilder(args);

// Add localization
builder.Services.AddLocalization(
    options => options
    .ResourcesPath = "Resources");

// Add session
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

// Configure cultures
builder.Services
    .Configure<RequestLocalizationOptions>(
    options =>
    {
        var cultures = new[]
        {
            "en-US", "es", "fr"
        };
        options.SetDefaultCulture("en-US");
        options.AddSupportedCultures(cultures);
        options.AddSupportedUICultures(cultures);
    });

var app = builder.Build();

// Use middleware (ORDER MATTERS!)
app.UseRequestLocalization();
app.UseSession();

app.Run();

🧠 Quick Recap

Concept What It Does Think Of It As…
Localization Shows content in user’s language A translator
Resource Files Stores translations A dictionary
Culture Config Sets language rules A costume
Culture Providers Detects user’s language A detective
Session State Remembers user data A memory box

🚀 You Did It!

Now you know how to:

  • ✅ Make your app speak multiple languages
  • ✅ Store translations in resource files
  • ✅ Configure cultures properly
  • ✅ Detect user language preferences
  • ✅ Remember user information with sessions

Your app is now a polyglot (someone who speaks many languages) AND has a great memory! 🌍🧠

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.