简体   繁体   中英

ASP.NET Core Model Binding Error Messages Localization in ASP.NET CORE 2.0

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."]);

Sample Project

I added the sample project for ASP.NET CORE 2.0 in the following repository:

Default Error Messages:

  • MissingBindRequiredValueAccessor : A value for the '{0}' property was not provided.
  • MissingKeyOrValueAccessor : A value is required.
  • MissingRequestBodyRequiredValueAccessor : A non-empty request body is required.
  • ValueMustNotBeNullAccessor : The value '{0}' is invalid.
  • AttemptedValueIsInvalidAccessor : The value '{0}' is not valid for {1}.
  • NonPropertyAttemptedValueIsInvalidAccessor : The value '{0}' is not valid.
  • UnknownValueIsInvalidAccessor : The supplied value is invalid for {0}.
  • NonPropertyUnknownValueIsInvalidAccessor : The supplied value is invalid.
  • ValueIsInvalidAccessor : The value '{0}' is invalid.
  • ValueMustBeANumberAccessor : The field {0} must be a number.
  • NonPropertyValueMustBeANumberAccessor : The field must be a number.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM