Skip to content

Wrong culture returned from CultureInfo.GetCultureInfo("") #115913

Closed
@podliy16

Description

@podliy16

Description

CultureInfo returns "Unknown Language" for empty string instead of InvariantCulture

The CultureInfo.GetCultureInfo("") method incorrectly returns a cached "Unknown Language" culture instead of the Invariant Culture as specified in the documentation.

Reference:
https://learn.microsoft.com/en-us/dotnet/api/System.Globalization.CultureInfo.GetCultureInfo?view=net-8.0#system-globalization-cultureinfo-getcultureinfo(system-string)

Documentation explicitly states:

If name is String.Empty, the method returns the invariant culture. This is equivalent to retrieving the value of the InvariantCulture property.

Current Behavior:
The method appears to be caching and returning an "Unknown Language" culture instead of the expected InvariantCulture when an empty string is provided.

This issue affects real-world applications, particularly when using Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.localization.requestlocalizationmiddleware?view=aspnetcore-9.0).

In our case:
Clients send Accept-Language: und header.
This results in calls to GetCultureInfo("und"), which cache Unknown Language culture under empty string key.
The unexpected "Unknown Language" culture causes application crashes since we only expected InvariantCulture per the documentation

Reproduction Steps

using System.Globalization;

var tmp = 5.42;
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("");
Console.WriteLine($"{tmp:F2}");
CultureInfo.GetCultureInfo("und");
Console.WriteLine($"{tmp:F2}");
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("");
Console.WriteLine($"{tmp:F2}");

Expected behavior

Doesn't crash, returns invariant culture.

Actual behavior

Crash with exception, because Unknown Language culture is not usable

Regression?

I don't think so

Known Workarounds

Currently, we don't have a clean solution for this issue. As a temporary measure, we're considering implementing a custom middleware with our own caching mechanism that properly handles empty culture strings by explicitly returning CultureInfo.InvariantCulture, or something like this.

Configuration

The issue has been reproduced on:

Windows 11 with .NET 9
Ubuntu 22.04.5 LTS (WSL) with .NET 8

We have reproduced it in production from official docker images as well, I'll add versions later, don't have access for specific tag right now.

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions