简体   繁体   中英

Localization for ASP.NET Core 3.0 doesn't work

As the title says localization doesn't work, I get only key not the value here is all necessary code.

ConfigurationServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddControllersWithViews();
        services.AddRazorPages();

        services.AddLocalization(options => options.ResourcesPath = "Resources");
        services.AddMvc().AddDataAnnotationsLocalization().AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix, options =>
        options.ResourcesPath = "Resources");

        services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new[]
            {
                new CultureInfo("en"),
                new CultureInfo("sr")
            };

            options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en");
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;

        });
    }

Configure

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        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();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseRequestLocalization();

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

Controller

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    public IStringLocalizer<Resource> _localizer;

    public HomeController(
        ILogger<HomeController> logger,
        IStringLocalizer<Resource> localizer)
    {
        _logger = logger;
        _localizer = localizer;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HandleError]
    public IActionResult Privacy()
    {
        throw new Exception();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Resource

namespace WebApplication.Resources
{
    public class Resource
    {
    }
}

Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}

@using Microsoft.Extensions.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using WebApplication.Resources

@inject IStringLocalizer<Resource> localizer
@inject IViewLocalizer _localizer

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <p>@localizer["Hello"]</p>
    <p>@_localizer["Hello"]</p>
</div>

Solution Explorer

In Resources folder I have class Resource and two .resx files (Resource.en.resx, Resource.sr.resx) they both contain one key Hello. In the view I'm trying to display value of that key with IStringLocalizer and with IViewLocalizer but without luck. Can someone tell me where is the problem, what am I doing wrong!

You have to be careful with the namespace of the class you are acquiring the IStringLocalizer for. From the documentation :

Resources are named for the full type name of their class minus the assembly name.

The full type name of your Resource class is WebApplication.Resources.Resource and subtracting the assembly name you get Resources.Resource . Also you have specified "Resources" as the root path for your resource files ( services.AddLocalization(options => options.ResourcesPath = "Resources") ). This means when you acquire IStringLocalizer<Resource> it'll try to locate your resource file at <project root>/Resources/Resources.Resource.en.resx (for English localization).

You have a few options:

1. Modify namespace of your Resource class

In your Resource.cs use the following namespace:

namespace WebApplication
{ ... }

Now the localizer will look for the resource file at <project root>/Resources/Resource.en.resx (or <project root>/Resources.Resource.en.resx - dots or path separators don't matter)

2. Rename your RESX files

Since the localizer is currently looking for the file at <project root>/Resources/Resources.Resource.en.resx you could simply rename your Resource.en.resx to Resources.Resource.en.resx

3. Don't set relative ResourcesPath

In Startup.cs when you configure localization you can skip setting ResourcesPath so that the localizer will look for the file relative to the projects root folder:

// Startup.cs -> ConfigureServices()
services.AddLocalization();

Now the localizer will look for the file at the path <project root>/Resources/Resource.en.resx .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM