我知道这很旧,但这是我在寻找答案时遇到的第一篇文章。这是我解决问题的方法:
public class CustomBodyModelValidator : ObjectModelValidator
{
public CustomBodyModelValidator(IModelMetadataProvider modelMetadataProvider, IList<IModelValidatorProvider> validatorProviders)
: base(modelMetadataProvider, validatorProviders) { }
public override ValidationVisitor GetValidationVisitor(ActionContext actionContext, IModelValidatorProvider validatorProvider,
ValidatorCache validatorCache, IModelMetadataProvider metadataProvider, ValidationStateDictionary validationState)
{
return new(actionContext, validatorProvider, validatorCache, metadataProvider, validationState)
{
ValidateComplexTypesIfChildValidationFails = true
};
}
public override void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model,
ModelMetadata metadata, object container)
{
//TODO: put your logic here
base.Validate(actionContext, validationState, prefix, model, metadata, container);
}
}
然后将其注册到Startup.cs
:
services.AddSingleton<IObjectModelValidator>(provider =>
{
var metadataProvider = provider.GetRequiredService<IModelMetadataProvider>();
var options = provider.GetRequiredService<IOptions<MvcOptions>>().Value;
return new CustomBodyModelValidator(metadataProvider, options.ModelValidatorProviders);
});