0

We have a custom DateTimeModelBinder that used to work fine with ASP.NET Core 1.1, but after upgrading to 2.2, it fails. This is the breaking part:

            bindingContext.ModelState.TryAddModelError(
                    bindingContext.ModelName,
                    bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(
                        valueProviderResult.ToString()));

The error is:

Method not found: 'Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.IModelBindingMessageProvider Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata.get_ModelBindingMessageProvider()'.

The failing part is:

bindingContext.ModelMetadata.ModelBindingMessageProvider

Obviously something has changed. I found this message explaining a bit about this breaking change, but all of it:

https://github.com/aspnet/Announcements/issues/240

Apparently we have to use DefaultModelBindingMessageProvider now, but how does the whole application share a common one, inluding model binders?

Problem is, in ModelBinders, the bindingContext.ModelMetadata.ModelBindingMessageProvider used to poing at a class containing the strings, but now is pointing to the abstract class and hence fails with the above error.

Using this instead works, but newing up this class for each use seems wrong (also, changes to the translations would not be reflected).

            bindingContext.ModelState.TryAddModelError(
                    bindingContext.ModelName,
                    new DefaultModelBindingMessageProvider().ValueMustNotBeNullAccessor(
                        valueProviderResult.ToString()));

I feel I should be able to set the ModelBindingMessageProvider property of the ModelMetadata in the bindingContext in my Startup.cs, but haven't found out how (or if I am on the right track). Am I?

galmok
  • 869
  • 10
  • 21

1 Answers1

0

It actually does work as the first code snippet shows. My problem was that the code shown was in a nuget package that depended on Microsoft.AspNetCore.Mvc version 1.1.3. In the project where I used the nuget package, I had simply overridden Microsoft.AspNetCore.Mvc to version 2.2.0 and assumed this was good enough (code was the same for both implementations).

But I assumed wrong: The code is identical, but the ModelBindingMessageProvider was changed to an abstract class/object (from a normal class/object) and using the compiled nuget package for 1.1.3 hence continued to point at the wrong type that was not/could not be updated by the 2.2.0 aspnetcore. Upgrading the dependency in nuget package to 2.2.0 made the nuget package work just fine.

galmok
  • 869
  • 10
  • 21