using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Localization;
using System.Globalization;
namespace DigitalData.Core.API
{
///
/// Provides extension methods for configuring localization services in an ASP.NET Core application.
/// These methods simplify the integration of cookie-based localization by setting up resource paths
/// and defining supported cultures.
///
public static class LocalizationExtensions
{
///
/// Adds localized resources and view localization services to the application.
///
/// The IServiceCollection to add services to.
/// The path to the resource files used for localization.
/// The IServiceCollection for chaining.
public static IServiceCollection AddCookieBasedLocalizer(this IServiceCollection services, string resourcesPath = "")
{
// Adds localization services with the specified resources path.
services.AddLocalization(options => options.ResourcesPath = resourcesPath)
// Adds MVC services with view localization and data annotations localization.
.AddMvc().AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
return services;
}
///
/// Configures the application to use cookie-based localization with support for multiple cultures.
///
/// The IApplicationBuilder to configure.
/// A params array of supported culture names.
/// The IApplicationBuilder for chaining.
public static IApplicationBuilder UseCookieBasedLocalizer(this IApplicationBuilder app, params string[] supportedCultureNames)
{
// Converts supported culture names into CultureInfo objects and checks for null or empty array.
IList supportedCultures = supportedCultureNames.Select(cn => new CultureInfo(cn)).ToList();
var defaultCultureInfo = supportedCultures.FirstOrDefault() ??
throw new ArgumentNullException(nameof(supportedCultureNames), "Supported cultures cannot be empty.");
// Configures localization options including default and supported cultures.
var options = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(culture: defaultCultureInfo.Name, uiCulture: defaultCultureInfo.Name),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
options.RequestCultureProviders.Add(new QueryStringRequestCultureProvider());
// Applies the localization settings to the application.
app.UseRequestLocalization(options);
return app;
}
}
}