Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not work ASP.NET Core Localization

I created an empty project.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(s => s.ResourcesPath = "Resources");
    var supportedCultures = new CultureInfo[]
    {
        new CultureInfo("de-CH"),
        new CultureInfo("en-GB"),
    };

    services.Configure<RequestLocalizationOptions>(s =>
    {
        s.SupportedCultures = supportedCultures;
        s.SupportedUICultures = supportedCultures;
        s.DefaultRequestCulture = new RequestCulture(culture: "de-CH", uiCulture: "de-CH");
    });

    services.AddMvc()
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization();
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{

    app.UseStaticFiles();

    // Using localization 
    var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(locOptions.Value);

    app.UseMvc();
}

Folder Structure

Resources
|
|--Controllers 
|       HomeController.de.resx
|       HomeController.en.resx
|       HomeController.resx

Controller

public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _stringLocalizer;

    public HomeController(IStringLocalizer<HomeController> stringLocalizer)
    {
        _stringLocalizer = stringLocalizer;
    }

    public IActionResult Index()
    {
        string testValue = _stringLocalizer["Test"];
        return View();
    }
}

I'm new about asp.net core, I'm just trying to understand, Why testValue always return Test, it's a bit confusing. I'm doing something wrong? i will be happy if u help me.

like image 567
Fatih Erol Avatar asked Mar 21 '18 18:03

Fatih Erol


People also ask

Does .NET core have global ASAX?

Global. ASP.NET Core introduced a new mechanism for bootstrapping an app. The entry point for ASP.NET applications is the Global. asax file. Tasks such as route configuration and filter and area registrations are handled in the Global.

What is localization in .NET framework?

Localization is the process of translating an application's resources into localized versions for each culture that the application will support. You should proceed to the localization step only after completing the Localizability review step to verify that the globalized application is ready for localization.


1 Answers

Just add the package Microsoft.Extensions.Localization
After do that, it works.
The ResourcePath is optional, and if you leave it null, the resource files organization style is the same that classic Asp.Net application (in the same location of the target classes).

like image 132
Thiago Daher Avatar answered Nov 15 '22 15:11

Thiago Daher