SajjadZare
SajjadZare

Reputation: 2378

Force localization be in specific language in specific controller

I have a web-api project that has several controllers, I implemented localization (English and Korean) for it but want one or two controllers return messages in English even when the language is Korean (don't want use simple English message and want to read from English resource)

Is it possible?

I setup localization like below:

 services.Configure<RequestLocalizationOptions>(options =>
            {
                var cultures = new List<CultureInfo> {
                    new CultureInfo("en"),
                    new CultureInfo("kr")
                };
                options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en");
                options.SupportedCultures = cultures;
                options.SupportedUICultures = cultures;
            });

            services.AddMvc().AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>factory.Create(typeof(SharedTranslate));
            });
            services.AddLocalization(o =>
            {
                o.ResourcesPath = "Resources";
            });

and in constructor :

public AuthAdminController(IStringLocalizer<SharedTranslate> localizer,...

I use below code in constructor of controller but didn't work

//First
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            //Second
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en");

Upvotes: 1

Views: 1513

Answers (1)

user1672994
user1672994

Reputation: 10839

Use the following code while retrieving the localized string in AuthAdminController

 CultureInfo.CurrentUICulture = new CultureInfo("<<Your language Code>>");
 var localizedString = localizer[resourceKey].Value;
 CultureInfo.CurrentUICulture = new CultureInfo("<<Reset to default one>>");
 return localizedString;

The first line setting the CurrentUICulture and 3rd line resetting to default one.

Upvotes: 5

Related Questions