Skip to content

Model binder polymorphic example - probably contains error #22198

@ArtemMelnychenko

Description

@ArtemMelnychenko

I have encountered a tricky issue with using the polymorphic model binder example. Here are the steps I have performed:

  1. Created model hierarchy (BaseClass, DerivedClass1 -> BaseClass, DerivedClass2 -> BaseClass)
  2. Created custom model binder using the example on the page
  3. Added few validation attributes on the base and derived class
  4. Submitted completely valid model
  5. Received result:
{
    "errors": {},
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-9834a72009df584a8e0c3af809ea270c-afc6e5b8fa916f42-00"
}

It was very confusing because there is no error in the model, but the result is 400.
Finally, I've been able to resolve the issue using this answer - https://stackoverflow.com/a/64908680. It says that this page contains an error. instead of this

// Setting the ValidationState ensures properties on derived types are correctly 
bindingContext.ValidationState[newBindingContext.Result] = new ValidationStateEntry
{ Metadata = modelMetadata };

should be this:

// Setting the ValidationState ensures properties on derived types are correctly 
bindingContext.ValidationState[newBindingContext.Result.Model] = new ValidationStateEntry
{ Metadata = modelMetadata };

After making the changes above, validation started to work as expected.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions