【问题标题】:Localization for ASP.NET Core 3.0 doesn't workASP.NET Core 3.0 的本地化不起作用
【发布时间】:2021-01-20 16:14:31
【问题描述】:

正如标题所说的本地化不起作用,我得到的只是 key 而不是这里的 value 是所有必要的代码。

配置服务

    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;

        });
    }

配置

    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();
        });
    }

控制器

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 });
    }
}

资源

namespace WebApplication.Resources
{
    public class Resource
    {
    }
}

索引.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

在 Resources 文件夹中,我有类 Resource 和两个 .resx 文件(Resource.en.resx、Resource.sr.resx),它们都包含一个键 Hello。在视图中,我尝试使用 IStringLocalizer 和 IViewLocalizer 显示该键的值,但没有运气。谁能告诉我问题出在哪里,我做错了什么!

【问题讨论】:

    标签: c# asp.net-core .net-core localization


    【解决方案1】:

    您必须小心获取IStringLocalizer 的类的命名空间。来自the documentation

    资源以其类的完整类型名称减去程序集名称来命名。

    Resource 类的完整类型名称是 WebApplication.Resources.Resource 并减去您得到的程序集名称 Resources.Resource。您还指定了“资源”作为资源文件的根路径 (services.AddLocalization(options =&gt; options.ResourcesPath = "Resources"))。这意味着当您获得IStringLocalizer&lt;Resource&gt; 时,它会尝试在&lt;project root&gt;/Resources/Resources.Resource.en.resx 找到您的资源文件(用于英文本地化)。

    你有几个选择:

    1。修改资源类的命名空间

    在您的 Resource.cs 中使用以下命名空间:

    namespace WebApplication
    { ... }
    

    现在本地化程序将在 &lt;project root&gt;/Resources/Resource.en.resx(或 &lt;project root&gt;/Resources.Resource.en.resx - 点或路径分隔符无关紧要)处查找资源文件

    2。重命名您的 RESX 文件

    由于本地化程序当前正在 &lt;project root&gt;/Resources/Resources.Resource.en.resx 查找文件,您只需将您的 Resource.en.resx 重命名为 Resources.Resource.en.resx

    3。不要设置相对 ResourcesPath

    Startup.cs 中,当您配置本地化时,您可以跳过设置ResourcesPath,以便本地化程序查找相对于项目根文件夹的文件:

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

    现在本地化程序将在路径 &lt;project root&gt;/Resources/Resource.en.resx 处查找文件。

    【讨论】:

    • 谢谢您,先生。你是英雄!
    猜你喜欢
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多