![](/img/trans.png)
[英]Using DataAnnotation localizer in your extension method for HtmlHelper in ASP.net core mvc 3.1
[英]How to properly use resource files with string localizer in .NET Core 3.1?
我有一個項目,我使用資源文件來存儲一些文本,我還嘗試使用 StringLocalizer<> 從資源文件中獲取所需的消息。 我已經在 Startup 類中配置了本地化設置,如下所示:
internal static class LocalizationConfiguration
{
private const string ResourcesPath = "Resources";
private const string DefaultCulture = "en-US";
internal static IServiceCollection ConfigureLocalizationSettings(this IServiceCollection services) =>
services
.AddLocalization(options =>
options.ResourcesPath = ResourcesPath);
internal static IApplicationBuilder UseRequestLocalizationMiddleware(this IApplicationBuilder builder) =>
builder
.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(DefaultCulture),
SupportedCultures = new List<CultureInfo>
{
new CultureInfo(DefaultCulture)
}
});
}
我的解決方案包括幾個項目。 我需要在包含我的業務邏輯的項目中使用 StringLocalizer - xxx.Handlers。 我還創建了一個名為 xxx.Resources 的項目,用於存儲包含兩個目錄的資源:
這是我的 UserMessages 類(它是空的虛擬類,遵循https://docs.microsoft.com/pl-pl/aspnet/core/fundamentals/localization?view=aspnetcore-3.1 ):
public class UserMessages
{
}
我將 StringLocalizer 注入我的命令處理程序,然后像下面這樣使用它(UserConstants.UserNotFoundMessageKey 是好的):
var userEntity = await _userRepository.GetUserByIdAsync(command.UserId);
if (userEntity is null)
{
var message = _stringLocalizer[UserConstants.UserNotFoundMessageKey];
var statusCode = (int) HttpStatusCode.NotFound;
throw new CommandException(message, statusCode);
}
問題是,我的消息沒有以正確的方式本地化,表達式“_stringLocalizer[UserConstants.UserNotFoundMessageKey]”實際上返回 UserNotFoundMessageKey 的值而不是位於資源文件中的消息。 我究竟做錯了什么?? 如何正確本地化這些消息?
這是關於如何在單獨的項目中創建共享資源的完整工作解決方案:
在 ProjectA 中(在我的解決方案中是SharedResource3_1
):
1.Create Shared
folder with UserMessages
class and Create Resources
folder with Shared.UserMessages.en-US.resx
file(不知道你為什么創建Shared.UserMessages.en-US.Designer.cs
,但它似乎沒有用):
UserMessages.cs
:
namespace SharedResource3_1.Shared
{
public class UserMessages
{
}
}
Shared.UserMessages.en-US.resx
:
在 ProjectB 中(在我的解決方案中是MvcCore3_1
):
1.在ProjectA中添加項目引用:
Right-click
ProjectB Dependencies
並選擇Add Project Reference
然后選擇 ProjectA:
然后你可以得到如下參考:
2.Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//add this...
LocalizationConfiguration.ConfigureLocalizationSettings(services);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//add this...
LocalizationConfiguration.UseRequestLocalizationMiddleware(app);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
internal static class LocalizationConfiguration
{
private const string ResourcesPath = "Resources";
private const string DefaultCulture = "en-US";
internal static IServiceCollection ConfigureLocalizationSettings(this IServiceCollection services) =>
services
.AddLocalization(options =>
options.ResourcesPath = ResourcesPath);
internal static IApplicationBuilder UseRequestLocalizationMiddleware(this IApplicationBuilder builder) =>
builder
.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(DefaultCulture),
SupportedCultures = new List<CultureInfo>
{
new CultureInfo(DefaultCulture)
}
});
}
3.家庭控制器:
using SharedResource3_1.Shared; //add the reference for the UserMessages in ProjectA
public class HomeController : Controller
{
private readonly IStringLocalizer<UserMessages> _stringLocalizer;
public HomeController(IStringLocalizer<UserMessages> stringLocalizer)
{
_stringLocalizer = stringLocalizer;
}
public IActionResult Index()
{
ViewBag.data = _stringLocalizer["cześć"]; //the key name should be the Name in your resx file...
return View();
}
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.