using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; namespace Microsoft.AspNet.Mvc.ModelBinding { /// /// This provides a required ModelValidator for members marked as [DataMember(IsRequired=true)]. /// public class DataMemberModelValidatorProvider : AssociatedValidatorProvider { protected override IEnumerable GetValidators(ModelMetadata metadata, IEnumerable attributes) { // Types cannot be required; only properties can if (metadata.ContainerType == null || string.IsNullOrEmpty(metadata.PropertyName)) { return Enumerable.Empty(); } if (IsRequiredDataMember(metadata.ContainerType, attributes)) { return new[] { new RequiredMemberModelValidator() }; } return Enumerable.Empty(); } internal static bool IsRequiredDataMember(Type containerType, IEnumerable attributes) { var dataMemberAttribute = attributes.OfType() .FirstOrDefault(); if (dataMemberAttribute != null) { // isDataContract == true iff the container type has at least one DataContractAttribute bool isDataContract = containerType.GetTypeInfo() .GetCustomAttributes() .OfType() .Any(); if (isDataContract && dataMemberAttribute.IsRequired) { return true; } } return false; } } }