【发布时间】:2018-07-02 18:34:54
【问题描述】:
最近我开始了一个 ASP.NET Core 2.0 解决方案。我需要在一个项目中分离 ViewModels 类以与其他项目共享。每个视图模型类都有其 DataAnnotations 属性,我需要使用全球化和本地化。每个使用 ViewModels 项目作为参考的项目在 Resources/Controllers 和 Resources/Views 文件夹中也有自己的语言资源。
后端项目中的 LoginViewModel.cs 示例:
public class LoginViewModel
{
[Required]
[Display(Name ="UserName")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password"))]
public string Password { get; set; }
}
根据MSDN documentation,我可以创建一个 SharedResource 类和一个 SharedResource.es.resx(不是像 SharedResource.resx 这样的默认资源文件),并通过使用以下方法在主 ASP.NET 项目中设置自定义类 DataAnnotation localizer Provider ConfigureServices 中的代码:
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(Backend.Resources.SharedResources));
});
在配置方法中:
var supportedCultures = new[]
{
new CultureInfo("es-CO")
};
app.UseRequestLocalization(new RequestLocalizationOptions()
{
DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
我尝试过之前提到的场景,但是当我运行应用程序时,使用 LoginViewModel 的登录 cshtml 会显示用户名和密码,而不是 SharedResource.es.resx 中的“Usuario”和“Contraseña”。 ¿ 不能在程序集中使用或注入 IStringLocalizer,所以我必须使用默认的资源文件?
我希望清楚!
【问题讨论】:
-
您找到解决方案了吗?
标签: c# asp.net asp.net-mvc asp.net-core-2.0