在ASP.NET CORE 1.1中,可以使用资源文件本地化模型绑定错误消息,并配置其选项以在Startup.cs中为ModelBindingMessageProvider设置消息访问器,如
services.AddMvc(options =>
{
var F = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var L = F.Create("ModelBindingMessages", null);
options.ModelBindingMessageProvider.ValueIsInvalidAccessor =
(x) => L["The value '{0}' is invalid."];
如下所示:ASP.NET Core Model Binding Error Messages Localization和此处:https://blogs.msdn.microsoft.com/mvpawardprogram/2017/05/09/aspnetcore-mvc-error-message/
在ASP.NET CORE 2.0中,我收到有关所有ModelBindingMessageProvider属性的错误消息
options.ModelBindingMessageProvider.ValueIsInvalidAccessor
只读
如何在ASP.NET CORE 2.0中本地化这些消息
答案 0 :(得分:2)
在ASP.NET Core 2.0中,模型绑定消息提供程序属性已只读,但已添加每个属性的setter方法。
因此,如果您按照我的linked post示例设置ValueIsInvalidAccessor
,则应使用SetValueIsInvalidAccessor
方法:
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor (
(x) => L["The value '{0}' is invalid."]);
我在以下存储库中添加了ASP.NET CORE 2.0的示例项目:
答案 1 :(得分:1)
我也碰到了这个。这些setter已替换为SetValueIsInvalidAccessor
等方法,此处描述了更改:https://github.com/aspnet/Announcements/issues/240
答案 2 :(得分:0)
您可以使用此配置来本地化mvc核心错误消息:
public class SomeMvcOptionsSetup : Microsoft.Extensions.Options.IConfigureOptions<Microsoft.AspNetCore.Mvc.MvcOptions>
{
private readonly Microsoft.Extensions.Localization.IStringLocalizer _resourceLocalizer;
public SomeMvcOptionsSetup()
{
}
public SomeMvcOptionsSetup(Microsoft.Extensions.Localization.IStringLocalizerFactory stringLocalizerFactory)
{
_resourceLocalizer = stringLocalizerFactory.Create(baseName:"ResourceClassName",location:"ResourceNameSpace");
}
public void Configure(Microsoft.AspNetCore.Mvc.MvcOptions options)
{
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) =>
{
if (_resourceLocalizer == null)
{
return "Custom Error Message";
}
return _resourceLocalizer["Specific Resource Key In Resource File"];
});
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) =>
{
if (_resourceLocalizer == null)
{
return "Value Can not be null....";
}
return _resourceLocalizer["ResourceKeyValueCanNotBeNull"];
});
.
.
.
}
}
然后,将以下内容添加到Startup.ConfigureServices(...)方法中:
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>,SomeMvcOptionsSetup >());
请参阅此link