2014-12-26 40 views
1

我期待根據數據庫中的值驗證特定的請求。這是一個複雜的場景,但我會嘗試在一個示例中簡化它。Web API中的動態驗證

說我有以下型號:

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進行搜索,然後檢查是否有值,但我不確定這是否是最好的方法。

然後我查看了Data Annotations,但沒有找到在運行時添加屬性的方法。

+0

不同於論壇的網站,我們不使用「謝謝」,或者「任何幫助表示讚賞」,或簽名型號[所以]。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed - 從 - 個)。 –

回答

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)檢查