다음을 사용하여 웹 API 요청의 유효성을 검사하기 위해 모델 유효성 검사를 사용하고 있습니다.
ActionFilterAttribute
속성 'A'에 종속 된 모델의 속성 'B'에 대한 유효성 검사 규칙을 가질 수 있습니까? 더 명확한 설명을 위해이 예제를 고려하십시오.
public class ValidationModel
{
[Required]
public int? Id { get; set; }
public string Barcode { get; set; }
public string BarcodeType { get; set; }
}
위 모델에는 필수 인 Id 속성이 있으며 선택적인 Barcode, BarcodeType 속성은 Barcode 속성에 값이있는 경우에만 BarcodeType 속성을 필수로 설정할 수 있습니다 (null이 아니고 빈 문자열 인 경우) )
.NET Framework를 구현하는 게시 된 ViewModel에 대해 자동으로 트리거되는 MVC의 사용자 지정 유효성 검사를위한 내장 메커니즘이 있습니다 IValidatableObject
.
예를 들면 :
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" });
}
}
}
테스트를 통해 컨트롤러에서 유효성 검사가 성공했는지 확인할 수 있습니다. ModelState.IsValid
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다