【发布时间】:2020-02-18 16:57:20
【问题描述】:
已将新的 .Resx 文件添加到 .Net Core Web 3 项目下的 Resources 文件夹中。
当尝试访问 resx 文件时,它在控制器或验证属性上不可用。
在 .Net Core 中使用 Resx 文件的正确方法是什么。
【问题讨论】:
-
请分享您的代码
标签: .net-core resx asp.net-core-3.0 .net-core-3.0
已将新的 .Resx 文件添加到 .Net Core Web 3 项目下的 Resources 文件夹中。
当尝试访问 resx 文件时,它在控制器或验证属性上不可用。
在 .Net Core 中使用 Resx 文件的正确方法是什么。
【问题讨论】:
标签: .net-core resx asp.net-core-3.0 .net-core-3.0
在Controller中配置本地化,可以参考以下步骤
1.在Startup.ConfigureServices方法中配置本地化,在Startup.Configure方法中设置文化。必须在任何可能检查请求文化的中间件之前配置本地化中间件:
public void ConfigureServices(IServiceCollection services)
{
//Adds the localization services to the services container. The code above also sets the resources path to "Resources"
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddControllersWithViews()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
}
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();
}
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fr"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
2.ConfigureServices方法将ResourcesPath设置为“Resources”,因此家庭控制器的法语资源文件的项目相对路径为Resources/Controllers.HomeController.fr.resx。或者,您可以使用文件夹来组织资源文件。对于家庭控制器,路径为Resources/Controllers/HomeController.fr.resx。
然后使用IStringLocalizer,它使用 ResourceManager 和 ResourceReader 在运行时提供特定于文化的资源来访问 Controller 中的 Resx 文件。
public class HomeController : Controller
{
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer)
{
_localizer = localizer;
}
public IActionResult About()
{
ViewData["Message"] = _localizer["Your application description page."];
return View();
}
}
更多详情,您可以参考official doc,其中包含示例代码和DataAnnotations 本地化。
【讨论】:
About.fr.cshtml 和about.en.cshtml,并且验证将像基于属性的验证一样工作。
我确实尝试过上面答案中解释的方式,但是太困惑了,似乎要完成很多事情要做。当我正在寻找可以使用资源文件的东西时,就像我们以前在 Asp.Net webforms 中所做的那样。我发现了一个不太复杂的解决方案,说我们可以使用Resource.ResourceManager.GetString("Hello", new CultureInfo("Ar"))
其中“Hello”是您从 Resource 字符串中使用的字符串键,“Ar”是您想要激活的文化。
这似乎不是最合适的方式,但它对我有用。我们可以管理从哪里获得文化到这个。我已经使用 Session 管理它。您可以从 Globalization and localization in ASP.NET Core With Resource Files 获得参考。您也可以查看他们的示例代码。
【讨论】: