【问题标题】:Dynamic Validation in Web APIWeb API 中的动态验证
【发布时间】:2014-12-26 17:33:18
【问题描述】:

我希望根据数据库中的值来验证特定请求。这是一个复杂的场景,但我将尝试在一个示例中对其进行简化。

假设我有以下模型:

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);

我从数据库中获取的信息会告诉我需要哪些属性,每个机构可能会有所不同。例如,一个机构可能需要姓名和年龄,而另一机构可能只需要姓名。需求对象看起来像这样:

public class Requirement
{
    public string PropertyName { get; set; }

    public bool IsRequired { get; set; }
}

那么,我的问题是,在将该模型提交到数据库之前对其进行验证的最佳方法是什么?理想情况下,我希望代理机构能够更改这些要求,因此,我希望尽可能避免硬编码验证。

我的第一个想法是调用一个需求列表,然后通过 PropertyName 搜索每个需求,然后检查是否有值,但我不确定这是否是最好的方法。

然后我查看了数据注释,但没有找到在运行时添加属性的方法。

【问题讨论】:

标签: c# asp.net validation asp.net-web-api


【解决方案1】:

您可以使用Fluent Validation library 并实现自定义验证器

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 注入到属性中。否则,您可以在属性中创建/使用特定的存储库。

一个非常好的事情是当您properly register your validator 时,您将能够使用默认的if (ModelState.IsValid) 检查来验证您的模型

【讨论】:

    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 2013-10-05
    • 2022-01-06
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多