Shared resource localization is not working

912 Views Asked by At

I am working on shared resource localization in Asp .Net Core 3.1. For that I created resource directory and created SharedResources.cs file.

Root/Resources/SharedResources.cs
Root/Resources/SharedResources.en.resx

I injected code in controller.

public AccountController(IStringLocalizer<SharedResources> sharedLocalizer)
{
_sharedLocalizer = sharedLocalizer;
}
public IActionResult Login(LoginViewModel model)
{
if(loginSuccess == true)
{
  return RedirectToAction("Dashboard", "Dashboard");
}
TempData["Error"] = _sharedLocalizer["Error"];
return View(model);

In SharedResources.en.resx

Key : Error
Value : Invalid User

In SharedResources.cs

namespace RootName
public class SharedResources
{
}

It displays Error and it should display Invalid User. Where am I wrong?

1

There are 1 best solutions below

0
On

For asp.net core 3.x,you need to create SharedResources.cs in your root folder and create SharedResources.en.resx in root/Resources folder like below:

enter image description here

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddLocalization(o =>
    {
        // We will put our translations in a folder called Resources
        o.ResourcesPath = "Resources";
    });
    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[]
            {
            new CultureInfo("en"),
            new CultureInfo("de"),
        };
        options.DefaultRequestCulture = new RequestCulture("en");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
    });       
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }


    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
    app.UseRequestLocalization(localizationOptions);

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });  
 }