IViewLocalizer 仅显示 .resx 文件中的密钥

问题描述 投票:0回答:1

我在 ASP.NET Core 本地化方面遇到问题。我想使用

IViewLocalizer
的方法。我有这个
program.cs
:

using xxx.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using System.Globalization;
using Microsoft.AspNetCore.Localization;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDbContext<XXX>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("XXX"));
});

builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()
                .AddDefaultUI();

builder.Services.AddControllersWithViews();

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

// Přidání podpory pro lokalizaci pohledů a datových anotací
builder.Services.AddControllersWithViews()
    .AddViewLocalization()
    .AddDataAnnotationsLocalization();

var app = builder.Build();

var supportedCultures = new[] { "en-US", "cs-CZ" };

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("cs-CZ"),
    SupportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("cs-CZ") },
    SupportedUICultures = new[] { new CultureInfo("en-US"), new CultureInfo("cs-CZ") }
});

app.UseRequestLocalization(app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);

using (var scope = app.Services.CreateScope())
{
    var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var roles = new[] { "Admin", "Redaktor", "Member" };
 
    foreach (var role in roles)
    {
        if (!await roleManager.RoleExistsAsync(role))
        {
            await roleManager.CreateAsync(new IdentityRole(role));
        }
    }
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == 404)
    {
        context.Request.Path = "/NotFound";
        await next();
    }
});

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

app.UseRouting();

app.UseAuthorization();

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

app.Run();

我的资源文件夹结构(目前我只尝试

_Layout.cshtml
):

资源文件夹

_Layout.cshtml
的标题:

@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@using System.Globalization

<!DOCTYPE html>
<html lang="cs">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - xxx</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/xxx.styles.css" asp-append-version="true" />
    <link rel="stylesheet" href="/css/bootsrap-custo-var.css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">
    @RenderSection("Styles", required: false)
</head>`
<body>
   <span>@Localizer["CookieSpanHeader"]</span>
</body>
</html>

此代码的输出是,它只显示键,而不是来自

.resx
(值)的文本。

我寻找问题的解决方案,但没有更好的结果

c# asp.net-core asp.net-core-mvc localization
1个回答
0
投票

您的 _Layout.cshtml 资源文件名不正确。根据资源文件名,文件名应该是:

_Layout.resx
_Layout.cs-CZ.resx

应排除扩展名 .cshtml

此外,您的配置不正确

RequestLocalizationOptions

添加以下代码:

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
   options.DefaultRequestCulture = new RequestCulture("cs-CZ");
   options.SupportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("cs-CZ") };
   options.SupportedUICultures = new[] { new CultureInfo("en-US"), new CultureInfo("cs-CZ") };
   options.RequestCultureProviders = new List<IRequestCultureProvider>
   {
       new UrlRequestCultureProvider()
   };
});

行前:

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

参考:使用自定义提供程序

并与

合作
app.UseRequestLocalization(app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);

您的Program.cs应如下所示:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDbContext<XXX>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("XXX"));
});

builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()
                .AddDefaultUI();

builder.Services.AddControllersWithViews();

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
   options.DefaultRequestCulture = new RequestCulture("cs-CZ");
   options.SupportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("cs-CZ") };
   options.SupportedUICultures = new[] { new CultureInfo("en-US"), new CultureInfo("cs-CZ") };
   options.RequestCultureProviders = new List<IRequestCultureProvider>
   {
       new UrlRequestCultureProvider()
   };
});

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

// Přidání podpory pro lokalizaci pohledů a datových anotací
builder.Services.AddControllersWithViews()
    .AddViewLocalization()
    .AddDataAnnotationsLocalization();

var app = builder.Build();

app.UseRequestLocalization(app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);

using (var scope = app.Services.CreateScope())
{
    var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var roles = new[] { "Admin", "Redaktor", "Member" };
 
    foreach (var role in roles)
    {
        if (!await roleManager.RoleExistsAsync(role))
        {
            await roleManager.CreateAsync(new IdentityRole(role));
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.