1

I have a simple ASP.Net Core app which uses razor. The user forms are generated by model and data annotation attributes. The error message of wrong input values are English by default. I knew that I can translate default message with help of 'ModelBindingMessageProvider'.

Below you can find a working way (in Startup.cs) by update the 'DefaultModelBindingMessageProvider':

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(o =>
    {
        // see: https://stackoverflow.com/questions/40828570/asp-net-core-model-binding-error-messages-localization
        o.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(u => "My custom validation error message");
    });
}

I would prefer not to configure the translation directly in the startup.cs. One way to do that is using a custom class which inherits from 'ModelBindingMessageProvider'.

public class MyModelBindingMessageProvider : ModelBindingMessageProvider
{
    public override Func<string, string> ValueMustNotBeNullAccessor => o => "My custom validation error message";
}

Here is my question:

  1. Where register My own class?
  2. Is this a good way? What is best practice at the moment?

(the real app uses string resources of course)

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Alois
  • 361
  • 2
  • 18
  • This might help a little? https://blogs.msdn.microsoft.com/mvpawardprogram/2017/05/09/aspnetcore-mvc-error-message/ – jpgrassi Mar 07 '19 at 08:37
  • Thanks for the feedback but that doc does not help. He describes before the breaking changes was done (see: https://github.com/aspnet/Announcements/issues/240). – Alois Mar 07 '19 at 08:40
  • did you ever figure this out? I agree with you. It seems better than putting the translations in the Startup class. – imokaythanks Aug 05 '19 at 22:00

1 Answers1

0

Unfortunately it looks like it's not possible to provide a custom implementation of ModelBindingMessageProvider in ASP.NET Core 3.1.

The constructor of MvcOptions sets the ModelBindingMessageProvider property to an instance of DefaultModelBindingMessageProvider.

ModelBindingMessageProvider = new DefaultModelBindingMessageProvider();

And the property itself has no setter and is not of type ModelBindingMessageProvider.

public DefaultModelBindingMessageProvider ModelBindingMessageProvider { get; }

tl;dr Even though the option of having an own implementation would make sense here, you have to configure the messages in the Startup class.

Chris
  • 591
  • 5
  • 6