У меня есть 2 проекта:
- Проект DataAccess с моделями и аннотациями к данным (например, RequiredAttribute)
- Веб-проект с представлениями MVC и т. д.
Я не хочу иметь отдельные языковые файлы для моделей/представлений и т. д.
В документации Microsoft не очень четко описано использование файла SharedResources.resx с локализованными сообщениями DataAnnotation.
В MVC 5 я об этом не позаботился. Мне нужно было только установить локаль на мой язык, и все было в порядке.
Я попытался установить ErrorMessageResourceName и ErrorMessageResourceType для имени моего общего файла ресурсов «Strings.resx» и «Strings.de.resx» в проекте DataAccess:
Код: Выделить всё
[Required(ErrorMessageResourceName = "RequiredAttribute_ValidationError", ErrorMessageResourceType = typeof(Strings))]
Я уже добавил .AddDataAnnotationsLocalization() в Startup.cs – но, похоже, он ничего не делает.
Я прочитал несколько статей, но не смог найти причину, почему это не работает.
РЕДАКТИРОВАТЬ:
Что у меня есть:
1.) Класс LocService
Код: Выделить всё
public class LocService
{
private readonly IStringLocalizer _localizer;
public LocService(IStringLocalizerFactory factory)
{
_localizer = factory.Create(typeof(Strings));
}
public LocalizedString GetLocalizedHtmlString(string key)
{
return _localizer[key];
}
}
3.) Добавлен файл Strings.de-DE.resx с одним элементом «RequiredAttribute_ValidationError»
4.) Изменен мой Startup.cs
Код: Выделить всё
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient();
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSingleton();
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.AddDataAnnotationsLocalization(
options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(Strings));
});
services.Configure(
opts =>
{
var supportedCultures = new List
{
new CultureInfo("de-DE"),
};
opts.DefaultRequestCulture = new RequestCulture("de-DE");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var locOptions = app.ApplicationServices.GetService();
app.UseRequestLocalization(locOptions.Value);
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
https://damienbod.com/2017/11/01/shared ... -core-mvc/
Имейте в виду, что мои модели хранятся в отдельном проекте.
Подробнее здесь: https://stackoverflow.com/questions/487 ... t-core-2-0
Мобильная версия