Claude
Skills
Sign in
Back

localization-globalization

Included with Lifetime
$97 forever

Multi-language support, resource files, culture formatting, and globalization patterns for ASP.NET Core Razor Pages applications. Use when implementing multi-language support in ASP.NET Core applications, managing resource files for translations, or formatting dates, numbers, and currencies for different cultures.

General

What this skill does


## Rationale

Global applications require support for multiple languages, cultures, and formatting conventions. Poor localization implementation leads to maintenance nightmares, inconsistent user experiences, and hard-to-find bugs with dates, numbers, and currencies. These patterns provide a maintainable approach to building truly global Razor Pages applications.

## Patterns

### Pattern 1: Resource File Structure

Organize resources by feature with proper naming conventions and culture hierarchy.

```
/Pages
  /Shared
    _Layout.cshtml
    Resources/
      _Layout.resx          (default/en)
      _Layout.es.resx       (Spanish)
      _Layout.fr.resx       (French)
      _Layout.de.resx       (German)
  /Account
    Login.cshtml
    Login.cshtml.cs
    Resources/
      Login.resx
      Login.es.resx
      Login.fr.resx
  /Products
    Index.cshtml
    Resources/
      Index.resx
      Index.es.resx
/Resources  (Shared resources)
  SharedResources.resx
  SharedResources.es.resx
  ValidationMessages.resx
```

```csharp
// SharedResources.cs - Type-safe resource access
public class SharedResources
{
    // This class is just a marker for IStringLocalizer<SharedResources>
}

// Strongly-typed resources with code generator
public static class ResourceKeys
{
    public const string WelcomeMessage = "WelcomeMessage";
    public const string SaveButton = "SaveButton";
    public const string CancelButton = "CancelButton";
    public const string ErrorOccurred = "ErrorOccurred";
    public const string RequiredField = "RequiredField";
}
```

### Pattern 2: Localization Configuration

Configure request localization with proper culture detection and fallback.

```csharp
// Program.cs
var supportedCultures = new[]
{
    new CultureInfo("en-US"),
    new CultureInfo("en-GB"),
    new CultureInfo("es-ES"),
    new CultureInfo("es-MX"),
    new CultureInfo("fr-FR"),
    new CultureInfo("de-DE")
};

builder.Services.AddLocalization(options =>
{
    options.ResourcesPath = "Resources";
});

builder.Services.AddRequestLocalization(options =>
{
    options.DefaultRequestCulture = new RequestCulture("en-US");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
    
    // Culture detection order:
    // 1. Query string (?culture=es-ES)
    // 2. Cookie (.AspNetCore.Culture)
    // 3. Accept-Language header
    // 4. Default culture
    options.RequestCultureProviders = new List<IRequestCultureProvider>
    {
        new QueryStringRequestCultureProvider(),
        new CookieRequestCultureProvider(),
        new AcceptLanguageHeaderRequestCultureProvider()
    };
});

// Register view localization
builder.Services.AddRazorPages()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization(options =>
    {
        options.DataAnnotationLocalizerProvider = (type, factory) =>
            factory.Create(typeof(SharedResources));
    });

// Middleware placement (must be before routing)
var app = builder.Build();
app.UseRequestLocalization();
app.UseRouting();
app.MapRazorPages();
```

### Pattern 3: Razor Pages Localization

Implement view and PageModel localization with proper resource injection.

```csharp
// PageModel with localization
public class ProductEditModel : PageModel
{
    private readonly IStringLocalizer<ProductEditModel> _localizer;
    private readonly IStringLocalizer<SharedResources> _sharedLocalizer;
    private readonly ILogger<ProductEditModel> _logger;

    public ProductEditModel(
        IStringLocalizer<ProductEditModel> localizer,
        IStringLocalizer<SharedResources> sharedLocalizer,
        ILogger<ProductEditModel> logger)
    {
        _localizer = localizer;
        _sharedLocalizer = sharedLocalizer;
        _logger = logger;
    }

    [BindProperty]
    public ProductInput Input { get; set; } = new();

    public string PageTitle => _localizer["EditProductTitle"];

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        try
        {
            await SaveProductAsync(Input);
            
            TempData["SuccessMessage"] = _localizer["ProductSaved"];
            return RedirectToPage("/Products/Index");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to save product");
            ModelState.AddModelError(string.Empty, _sharedLocalizer["ErrorOccurred"]);
            return Page();
        }
    }
}

// View with localization
@page "{id:guid}"
@model ProductEditModel
@inject IStringLocalizer<SharedResources> SharedLocalizer
@inject IViewLocalizer ViewLocalizer

@{
    ViewData["Title"] = Model.PageTitle;
}

<h1>@ViewLocalizer["EditProductTitle"]</h1>

<form method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    
    <div class="form-group">
        <label asp-for="Input.Name">@ViewLocalizer["ProductName"]</label>
        <input asp-for="Input.Name" class="form-control" 
               placeholder="@ViewLocalizer["NamePlaceholder"]" />
        <span asp-validation-for="Input.Name" class="text-danger"></span>
    </div>
    
    <div class="form-group">
        <label asp-for="Input.Price">@ViewLocalizer["Price"]</label>
        <input asp-for="Input.Price" class="form-control" 
               type="number" step="0.01" />
        <small class="form-text text-muted">
            @ViewLocalizer["PriceHelpText"]
        </small>
    </div>
    
    <button type="submit" class="btn btn-primary">
        @SharedLocalizer["SaveButton"]
    </button>
    <a asp-page="/Products/Index" class="btn btn-secondary">
        @SharedLocalizer["CancelButton"]
    </a>
</form>
```

### Pattern 4: Culture-Specific Formatting

Use culture-aware formatting for dates, numbers, and currencies.

```csharp
// Extension methods for consistent formatting
public static class FormattingExtensions
{
    public static string ToCurrency(this decimal amount, IFormatProvider? provider = null)
    {
        return amount.ToString("C", provider ?? CultureInfo.CurrentCulture);
    }

    public static string ToShortDate(this DateTime date, IFormatProvider? provider = null)
    {
        return date.ToString("d", provider ?? CultureInfo.CurrentCulture);
    }

    public static string ToLongDate(this DateTime date, IFormatProvider? provider = null)
    {
        return date.ToString("D", provider ?? CultureInfo.CurrentCulture);
    }

    public static string ToCompactNumber(this int number, IFormatProvider? provider = null)
    {
        return number.ToString("N0", provider ?? CultureInfo.CurrentCulture);
    }
}

// View usage
@inject IStringLocalizer<SharedResources> Localizer

<div class="product-details">
    <p>@Localizer["PriceLabel"]: @Model.Product.Price.ToCurrency()</p>
    <p>@Localizer["AvailableFrom"]: @Model.Product.AvailableDate.ToLongDate()</p>
    <p>@Localizer["StockQuantity"]: @Model.Product.Stock.ToCompactNumber()</p>
</div>

// Culture-specific validation messages
public class ProductInput
{
    [Required(ErrorMessageResourceName = "RequiredField", 
              ErrorMessageResourceType = typeof(SharedResources))]
    [StringLength(100, ErrorMessageResourceName = "MaxLength",
                  ErrorMessageResourceType = typeof(SharedResources))]
    public required string Name { get; set; }

    [Range(0.01, 999999.99, ErrorMessageResourceName = "InvalidPrice",
           ErrorMessageResourceType = typeof(SharedResources))]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [DataType(DataType.Date)]
    [Display(ResourceType = typeof(SharedResources), Name = "AvailableDateLabel")]
    public DateTime AvailableDate { get; set; }
}
```

### Pattern 5: Language Switcher Implementation

Create a language switcher that persists culture selection.

```csharp
// Culture controller for switching languages
public class CultureController : Controller
{
    [HttpPost]

Related in General