我希望根据数据库中的值验证特定的请求。这是一个复杂的场景,但我将尝试在一个示例中简化它。
假设我有以下模式:
public class CustomerModel
{
public int AgencyId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}当POST请求传入时,我需要打个电话,以获得被传递的AgencyId的某些需求。
var requirements = _repository.GetRequirementsForAgency(model.AgencyId);我从数据库中得到的信息将告诉我哪些属性是必需的,这对于每个机构来说可能是不同的。例如,一个机构可能需要名称和年龄,而另一个机构可能只需要名称。requirements对象看起来如下所示:
public class Requirement
{
public string PropertyName { get; set; }
public bool IsRequired { get; set; }
}所以,我的问题是,在这个模型提交到数据库之前,最好的方法是什么?理想的情况是,我想让原子能机构能够改变这些要求,因此,如果可能的话,我想避免硬编码验证。
我的第一个想法是调用一个需求列表,然后通过PropertyName搜索每个需求,然后检查是否有一个值,但我不确定这是否是最好的方法。
然后,我研究了数据注释,但没有找到在运行时添加属性的方法。
发布于 2014-12-26 18:01:03
您可以使用Fluent验证库并实现自定义验证器。
public class CustomerModelValidator : AbstractValidator<CustomerModel>
{
private readonly IRepository _repository;
public RegisterModelValidator(IRepository repository)
{
this._repository= repository;
RuleFor(x => x.AgencyId).GreaterThan(0).WithMessage("Invalid AgencyId");
RuleFor(x => x.Age).GreaterThan(0).WithMessage("Invalid Age");
Custom(c =>
{
var requirements = _repository.GetRequirementsForAgency(model.AgencyId);
\\validate each property according to requirements object.
\\if (Validation fails for some property)
return new ValidationFailure("property", "message");
\\else
return null;
});
}
}如果在项目中使用依赖注入(我强烈建议),则必须将相关的IRepository注入到属性中。否则,您可以在属性中创建/使用特定的存储库。
一个非常好的事情是,当您正确注册您的验证程序时,您将能够使用默认的if (ModelState.IsValid)检查来验证您的模型。
https://stackoverflow.com/questions/27660049
复制相似问题