- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在新的 .NET Core 项目中遇到本地化问题。我有 2 个项目:
我的愿望是将所有验证属性全局本地化到一个地方,以实现与 MVC 5 类似的行为。这可能吗?
我不想为模型/ View 等使用单独的语言文件。
对于将 SharedResources.resx 文件与本地化 DataAnnotation 消息一起使用,Microsoft 文档不是很清楚。
在 MVC 5 中我没有处理它。我只需要将语言环境设置为我的语言,一切都很好。
我尝试将 ErrorMessageResourceName 和 ErrorMessageResourceType 设置为我在 DataAccess 项目中的共享资源文件名“Strings.resx”和“Strings.de.resx”:
[Required(ErrorMessageResourceName = "RequiredAttribute_ValidationError", ErrorMessageResourceType = typeof(Strings))]
我还尝试将设置名称设置为 RequiredAttribute_ValidationError - 但它不起作用。
我已经在 Startup.cs 中添加了 .AddDataAnnotationsLocalization()
- 但它似乎什么也没做。
我已经阅读了几篇文章,但找不到它不起作用的原因。
编辑:到目前为止我所拥有的:
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];
}
}
2.) 使用 Strings.cs 添加文件夹“Resources”(带有虚拟构造函数的空类)
3.) 添加了带有一项“RequiredAttribute_ValidationError”的 Strings.de-DE.resx 文件
4.) 修改我的 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MessageService>();
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSingleton<LocService>();
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<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new List<CultureInfo>
{
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<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
我已按照此处的说明进行操作,但它不起作用: https://damienbod.com/2017/11/01/shared-localization-in-asp-net-core-mvc/
请记住,我的模型保存在一个单独的项目中。
最佳答案
正如@Sven 在他对 Tseng's answer 的评论中指出的那样它仍然需要您明确指定 ErrorMessage
,这变得非常乏味。
问题出在逻辑ValidationAttributeAdapter<TAttribute>.GetErrorMessage()
用于决定是否使用提供的 IStringLocalizer
或不。我使用以下解决方案来解决该问题:
创建自定义 IValidationAttributeAdapterProvider
使用默认 ValidationAttributeAdapterProvider
的实现像这样:
public class LocalizedValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
private readonly ValidationAttributeAdapterProvider _originalProvider = new ValidationAttributeAdapterProvider();
public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
{
attribute.ErrorMessage = attribute.GetType().Name.Replace("Attribute", string.Empty);
if (attribute is DataTypeAttribute dataTypeAttribute)
attribute.ErrorMessage += "_" + dataTypeAttribute.DataType;
return _originalProvider.GetAttributeAdapter(attribute, stringLocalizer);
}
}
在 Startup.ConfigureServices()
中注册适配器调用前AddMvc()
:
services.AddSingleton<Microsoft.AspNetCore.Mvc.DataAnnotations.IValidationAttributeAdapterProvider, LocalizedValidationAttributeAdapterProvider>();
我更喜欢根据实际属性使用“更严格”的资源名称,因此上面的代码将查找诸如“Required”和“DataType_Password”之类的资源名称,但这当然可以通过多种方式进行自定义。
如果您更喜欢基于属性的默认消息的资源名称,您可以这样写:
attribute.ErrorMessage = attribute.FormatErrorMessage("{0}");
关于c# - ASP.NET Core 2.0 中 RequiredAttribute 的本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48769199/
RequiredAttribute 适用于 string 但不适用于 DateTime。例如: [Required] [DisplayFormat(ConvertEmptyString
我有一个必需的消息,我想给它一个自定义消息,因为默认消息不是很好。该消息必须来自资源文件并已参数化,因此资源文件中的消息将类似于 "The {0} field is required." 我需要能够用
我有一个 RequiredAttribute 的扩展类,它不会发回错误消息。如果我在调试器中检查它,文本就在那里。 public class VierRequired : RequiredAttrib
我的 Code-First 模型中有一个数据库计算字段。我已经用 DatabaseGeneratedAttribute 标记了它。我还需要指定 RequiredAttribute 吗? 换句话说:'r
我有一个 Comment 类,其中有一个 Author 属性: public class Comment : IEquatable { public int ID { get; set; }
我在新的 .NET Core 项目中遇到本地化问题。我有 2 个项目: 带有模型和 DataAnnotations 的 DataAccess 项目(例如 RequiredAttribute) 具有 M
这是我们在 .NET MVC 2 中面临的问题。 我们正在尝试使用 DataAnnotations 来为我们处理模型验证,就像它应该做的那样。我们遇到的唯一问题是我们不想要标准错误消息(因为我们的网站
我正在使用 javascript 非侵入式验证。我有一个 View 模型,我正在将其重新用于多种形式,并且在某些形式中,需要 View 模型上的某些属性。在其他形式上,他们不应该。有没有办法以编程方式
这是我们在 .NET MVC 2 中面临的问题。 我们正在尝试使用 DataAnnotations 来为我们处理模型验证,就像它应该做的那样。我们遇到的唯一问题是我们不想要标准错误消息(因为我们的网站
假设我向我的 API 发送了以下请求: POST http://localhost:4940/api/cars HTTP/1.1 User-Agent: Fiddler Host: localhost
Brad Wilson 发布了有关 ASP.NET MVC 新 ModelMetaData 的精彩博客系列: http://bradwilson.typepad.com/blog/2009/10/as
我试图创建一个自定义版本的 RequiredAttribute 来替换内置的版本,我已经让它适用于具有字符串值的属性,但是对于 DateTime 或整数的属性,例如,默认的 RequiredAttri
我是一名优秀的程序员,十分优秀!