gpt4 book ai didi

c# - 是否可以在 ASP.NET Core 中使用自定义 ModelState 验证提供程序?

转载 作者:行者123 更新时间:2023-12-02 17:47:07 24 4
gpt4 key购买 nike

我有以下 ASP.NET CORE 操作:

public async Task<IActionResult> Post([FromBody]Model model) { 

IValidator<Model> validator = new Validator<Model>();

Boolean valid = await validator.ValidateAsync(model);

if (!valid)
return HttpBadRequest(validator.GetErrors());

// Do something
}

除了在操作中定义验证器之外,如何将其与 IOC 和自定义 ModelState 验证提供程序集成?

最佳答案

首先,您需要实现您的自定义 IModelValidatorProviderIModelValidator .

请考虑我编写的这个简单示例:

public class MyCustomModelValidatorProvider : IModelValidatorProvider
{
public void CreateValidators(ModelValidatorProviderContext context)
{
if (context.ModelMetadata.MetadataKind == ModelMetadataKind.Type)
{
var validatorType = typeof(MyCustomModelValidator<>)
.MakeGenericType(context.ModelMetadata.ModelType);
var validator = (IModelValidator)Activator.CreateInstance(validatorType);

context.Results.Add(new ValidatorItem
{
Validator = validator,
IsReusable = true
});
}
}
}

public interface ISelfValidatableModel
{
string Validate();
}

public class MyCustomModelValidator<T> : IModelValidator where T : ISelfValidatableModel
{
public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
{
var model = (T)context.Model;

var error = model.Validate();

if (!string.IsNullOrEmpty(error))
{
return new List<ModelValidationResult>
{
new ModelValidationResult(model.ToString(), error)
};
}

return Enumerable.Empty<ModelValidationResult>();
}
}

您需要将自定义提供程序添加到 MVC 选项中:

services.AddMvc(options =>
{
options.ModelValidatorProviders.Add(new MyCustomModelValidatorProvider());
});

框架内置示例:

DataAnnotationsModelValidatorProvider.cs
DataAnnotationsModelValidator.cs

关于c# - 是否可以在 ASP.NET Core 中使用自定义 ModelState 验证提供程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36982370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com