Skip to content

Extend ModelError class with the ability to have custom validation properties and values #6661

Open
@kzaabox

Description

@kzaabox

Related item:

Improve validation for non-interactive consumption

Problem:

Currently it is not possible to attach custom properties to the model validation result object.
The ModelError class can only store a message (ErrorMessage property) for a validation error.
In most cases it is not enough because at least an ErrorCode should also be attached to it.

A possible solution:

By adding for example an IDictionary<string, object> ErrorDetails {get; set;} property to the ModelError class would enable the validation attributes to add additional data to a validation result.
The keys could be the names of the added properties.
It would also be great because with such an extended ModelError class, 3rd party model validators (e.g.: FluentValidation) could attach their validation properties to it.
See ValidationFailure class of FluentValidator.
It contains properties like CustomState, and ErrorCode which will be lost when someone using this library with the built-in validation logic of ASP.NET Core, because there is no place for those properties in the ModelError class.
Of course any other solution could work as long as it would be backward compatible with the current implementation.

Workaround:

In order to have the complete validation result of the FluentValidation.AspNetCore package, I wrote an ActionFilter and I attached it to every action methods for every controllers.
The input model validation is done manually in this filter by using FluentValidation and if there was any validation error, the request is short-circuited by setting the response object (an extended version of the ValidationProblemDetails).
With this method however I had to opt-out from the goodness of the new ControllerBase class (automatic BadRequest reponse on ModelState.IsValid == false) by setting the SuppressModelStateInvalidFilter property of the ApiBehaviorOptions in the ConfigureServices method of the startup code of the service.

Additionally the ValidationProblemDetails class also lack of the ability to have custom KV pairs for validation results.
So by extending the ModelError class would mean that the ValidationProblemDetails class should also be extended in order to have a response body at the end of the pipeline which would contain every additional validation properties and their values too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    affected-fewThis issue impacts only small number of customersarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-model-bindingseverity-blockingThis label is used by an internal tool

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions