In ASP.NET CORE 1.1 it was possible to localize model binding error messages using a resource file and configure its options to set message accessors for ModelBindingMessageProvider in the Startup.cs like
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."];
as shown here: ASP.NET Core Model Binding Error Messages Localization and here: https://blogs.msdn.microsoft.com/mvpawardprogram/2017/05/09/aspnetcore-mvc-error-message/
In ASP.NET CORE 2.0 I receive an error message on all of the ModelBindingMessageProvider's properties
options.ModelBindingMessageProvider.ValueIsInvalidAccessor
is readonly
How can these messages be localized in ASP.NET CORE 2.0
In ASP.NET Core 2.0, model binding message provider properties have got read only, but a setter method for each property has been added.
So if you follow the example of my linked post , to set ValueIsInvalidAccessor
, you should use SetValueIsInvalidAccessor
method this way:
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor (
(x) => L["The value '{0}' is invalid."]);
I added the sample project for ASP.NET CORE 2.0 in the following repository:
I also ran into this. These setters were replaced with methods such as SetValueIsInvalidAccessor
, the change is described here: https://github.com/aspnet/Announcements/issues/240
you could use this configuration for localize mvc core error messages :
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"];
});
.
.
.
}
}
Then, add the following to your Startup.ConfigureServices(...) method:
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>,SomeMvcOptionsSetup >());
Please see this link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.