具有依赖属性的asp.net Web API中的模型验证

时间:2016-06-17 07:46:43

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

我正在使用模型验证来验证web api请求:

  

ActionFilterAttribute

是否可以为模型的属性“B”设置验证规则,该规则取决于属性“A”。请考虑此示例以获得更多说明

public class ValidationModel
{

    [Required]
    public int? Id { get; set; }

    public string Barcode { get; set; }

    public string BarcodeType { get; set; }
}

上面的模型有一个必需的Id属性,Barcode,BarcodeType属性是可选的,当且仅当Barcode属性中有任何值时(如果它不是null),可以将BarcodeType属性设置为required。一个空字符串)

2 个答案:

答案 0 :(得分:2)

MVC中有一个内置的自定义验证机制,可以自动为已实现public class ValidationModel : IValidatableObject { // properties as defined above public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (!string.IsNullOrWhiteSpace(Barcode) && string.IsNullOrWhiteSpace(BarcodeType)) { yield new ValidationResult("BarcodeType is required if Barcode is given", new[] { "BarcodeType" }); } } } 的已发布ViewModel触发。

例如:

ModelState.IsValid

您可以通过测试检查控制器中的验证是否成功 Sub CSV_Import() Dim dateien, i, lastrow lastrow = 1 dateien = Application.GetOpenFilename _ ("csv-Dateien (*.csv), *.csv", MultiSelect:=True) Dim filename As String '******************************************************' filename = "D:/path/merged.csv" '******************************************************' Dim oFso: Set oFso = CreateObject("Scripting.FileSystemObject") Dim oSourceFile, oTargetFile Set oTargetFile = oFso.CreateTextFile(filename, True) Dim sArray() If IsArray(dateien) Then For i = 1 To UBound(dateien) ReDim sArray(0) Set oSourceFile = oFso.OpenTextFile(dateien(i), 1) ' open for reading While Not oSourceFile.AtEndOfStream ' while there is data in the file sArray(UBound(sArray)) = oSourceFile.ReadLine ' add the line to an array ReDim Preserve sArray(UBound(sArray) + 1) ' increase size of the array by 1 Wend ' Now we have the whole file in an array If i <> 1 Then ' Keep header from the first import For myLoop = 1 To UBound(sArray) ' Loop from 1 and we skip the header line in the file oTargetFile.WriteLine sArray(myLoop) ' write array values into file Next myLoop ' repeat for each line in the array Else For myLoop = 0 To UBound(sArray) ' Loop from 0 and we don't skip the header line in the file oTargetFile.WriteLine sArray(myLoop) ' write array values into file Next myLoop ' repeat for each line in the array End If Next i ' repeat for each file in dateien End If Call SortCSVFile() End Sub

答案 1 :(得分:0)

我会查看MVC Foolproof验证。它是一个易于使用的包,将为您提供多种方法来完成基于条件的模型验证。它提供了许多验证器,例如:

  • [RequiredIf]
  • [RequiredIfNot]
  • [RequiredIfTrue]
  • [RequiredIfFalse]
  • [RequiredIfEmpty]
  • [RequiredIfNotEmpty]
  • [RequiredIfRegExMatch]
  • [RequiredIfNotRegExMatch]

    它甚至适用于开箱即用的jQuery验证。 http://foolproof.codeplex.com/