【问题标题】:Shared resource localization is not working共享资源本地化不起作用
【发布时间】:2020-09-01 04:30:22
【问题描述】:

我正在 Asp .Net Core 3.1 中进行共享资源本地化。为此,我创建了资源目录并创建了 SharedResources.cs 文件。

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

我在控制器中注入了代码。

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

SharedResources.en.resx

Key : Error
Value : Invalid User

SharedResources.cs

namespace RootName
public class SharedResources
{
}

它显示错误并且应该显示Invalid User。我哪里错了?

【问题讨论】:

  • 嗨@Abhi,我的回答对你有帮助吗?如果有,你能accept as answer吗?如果没有,你能跟进让我知道吗?

标签: asp.net-core model-view-controller localization globalization shared-resource


【解决方案1】:

对于 asp.net core 3.x,您需要在根文件夹中创建 SharedResources.cs 并在 root/Resources 文件夹中创建 SharedResources.en.resx,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2014-02-11
    • 1970-01-01
    相关资源
    最近更新 更多