0

我正在研究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
{
}

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

4

1 回答 1

0

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

在此处输入图像描述

启动.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?}");
    });  
 }
于 2020-05-16T02:15:05.813 回答