ResourceManager retrieves a resource by key so an API response need not hardcode its description in one language. Resources can also be images, but string resources are enough for localized sensor descriptions. The class is in System.Resources and needs no separate NuGet package. section 12.2
Listing 12.7 Using ResourceManager to get localized sensor description
using System.Resources; #1
public class Measurement
{
private static readonly ResourceManager s_resMan = #2
new ("AcController.SensorNames", #3
typeof(Measurement).Assembly); #4
public string SensorName { get; set; }
public decimal Value { get; set; }
public string Description {
get => s_resMan.GetString(SensorName)!; #5
}
public Measurement(string sensorName, decimal value) #6
{
SensorName = sensorName;
Value = value;
}
}
Create the manager with the resource root name and containing assembly. Measurement uses its stable SensorName as the key when its Description getter calls GetString. section 12.2
Make the lookup usable:
- Put default key–value strings in SensorNames.restext. The root name AcController.SensorNames combines the assembly name and resource name; keys must remain consistent across languages. section 12.2
- Embed .restext files with an EmbeddedResource wildcard in the project file. Unlike ResX, ResText is a compact text format limited to strings. section 12.2
- Add SensorNames.es-MX.restext with Spanish-Mexico values for the same keys. Its culture-specific resources appear in an es-MX satellite assembly. If only an embedded resource changes, use dotnet build --no-incremental because an incremental build may miss it. section 12.3
Listing 12.12 Enabling ASP.NET Core culture provider
var cultures = new[] { "en-US", "es-MX" }; #1
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture(cultures[0]) #2
.AddSupportedCultures(cultures)
.AddSupportedUICultures(cultures); #3
app.UseRequestLocalization(localizationOptions);
Configure ASP.NET Core request localization with a default culture and supported cultures and UI cultures. Place the middleware before controller mapping; ResourceManager uses UI culture to choose resources, while culture governs formatting. section 12.4
Check both responses
Request the measurement endpoint normally and with ?culture=es-MX, then assert that the returned descriptions match the default and Spanish strings. The controller and Measurement constructor do not need a culture parameter: request localization establishes the culture used for resource lookup. A single parameterized test can check both cases. section 12.2 section 12.4
