本文整理汇总了C#中System.Web.Http.Metadata.ModelMetadata类的典型用法代码示例。如果您正苦于以下问题:C# ModelMetadata类的具体用法?C# ModelMetadata怎么用?C# ModelMetadata使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ModelMetadata类属于System.Web.Http.Metadata命名空间,在下文中一共展示了ModelMetadata类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Validate
public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
{
bool propertiesValid = true;
foreach (ModelMetadata propertyMetadata in metadata.Properties)
{
foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(ValidatorProviders))
{
foreach (ModelValidationResult propertyResult in propertyValidator.Validate(metadata, container))
{
propertiesValid = false;
yield return new ModelValidationResult
{
MemberName = ModelBindingHelper.CreatePropertyModelName(propertyMetadata.PropertyName, propertyResult.MemberName),
Message = propertyResult.Message
};
}
}
}
if (propertiesValid)
{
foreach (ModelValidator typeValidator in metadata.GetValidators(ValidatorProviders))
{
foreach (ModelValidationResult typeResult in typeValidator.Validate(metadata, container))
{
yield return typeResult;
}
}
}
}
示例2: GetValidators
public IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata)
{
// If metadata is for a property then containerType != null && propertyName != null
// If metadata is for a type then containerType == null && propertyName == null, so we have to use modelType for the cache key.
Type typeForCache = metadata.ContainerType ?? metadata.ModelType;
Tuple<Type, string> cacheKey = Tuple.Create(typeForCache, metadata.PropertyName);
ModelValidator[] validators;
if (!TryGetValue(cacheKey, out validators))
{
_cacheLock.EnterWriteLock();
try
{
// Check the cache again in case the value was computed and added to the cache while we were waiting on the write lock
if (!_validatorCache.TryGetValue(cacheKey, out validators))
{
// Compute validators
validators = metadata.GetValidators(_validatorProviders.Value).ToArray();
_validatorCache.Add(cacheKey, validators);
}
}
finally
{
_cacheLock.ExitWriteLock();
}
}
return validators;
}
示例3: Validate
public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
{
if (metadata.Model != null)
{
var selector = _customizations.ToValidatorSelector();
//var interceptor = _customizations.GetInterceptor() ?? (_validator as IValidatorInterceptor);
var context = new ValidationContext(metadata.Model, new PropertyChain(), selector);
//if (interceptor != null)
//{
// // Allow the user to provide a customized context
// // However, if they return null then just use the original context.
// context = interceptor.BeforeMvcValidation(ControllerContext, context) ?? context;
//}
var result = _validator.Validate(context);
//if (interceptor != null)
//{
// // allow the user to provice a custom collection of failures, which could be empty.
// // However, if they return null then use the original collection of failures.
// result = interceptor.AfterMvcValidation(ControllerContext, context, result) ?? result;
//}
if (!result.IsValid)
{
return ConvertValidationResultToModelValidationResults(result);
}
}
return Enumerable.Empty<ModelValidationResult>();
}
示例4: DefaultValues
public void DefaultValues()
{
// Arrange
Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();
// Act
ModelMetadata metadata = new ModelMetadata(provider.Object, typeof(Exception), () => "model", typeof(string), "propertyName");
// Assert
Assert.Equal(typeof(Exception), metadata.ContainerType);
Assert.True(metadata.ConvertEmptyStringToNull);
Assert.Null(metadata.DataTypeName);
Assert.Null(metadata.Description);
Assert.Null(metadata.DisplayFormatString);
Assert.Null(metadata.DisplayName);
Assert.Null(metadata.EditFormatString);
Assert.False(metadata.HideSurroundingHtml);
Assert.Equal("model", metadata.Model);
Assert.Equal(typeof(string), metadata.ModelType);
Assert.Null(metadata.NullDisplayText);
Assert.Equal(10000, metadata.Order);
Assert.Equal("propertyName", metadata.PropertyName);
Assert.False(metadata.IsReadOnly);
Assert.True(metadata.RequestValidationEnabled);
Assert.Null(metadata.ShortDisplayName);
Assert.True(metadata.ShowForDisplay);
Assert.True(metadata.ShowForEdit);
Assert.Null(metadata.TemplateHint);
Assert.Null(metadata.Watermark);
}
示例5: GetValidators
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
{
List<ModelValidator> results = new List<ModelValidator>();
// Produce a validator for each validation attribute we find
foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>())
{
DataAnnotationsModelValidationFactory factory;
if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory))
{
factory = DefaultAttributeFactory;
}
results.Add(factory(metadata, validatorProviders, attribute));
}
// Produce a validator if the type supports IValidatableObject
if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))
{
DataAnnotationsValidatableObjectAdapterFactory factory;
if (!ValidatableFactories.TryGetValue(metadata.ModelType, out factory))
{
factory = DefaultValidatableFactory;
}
results.Add(factory(metadata, validatorProviders));
}
return results;
}
示例6: Validate
public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
{
if (metadata.Model is string)
{
var dirty = (string) metadata.Model;
var sanitized = Sanitizer.GetSafeHtmlFragment(dirty);
if (!dirty.Equals(sanitized))
{
// Revert HTML encoded special characters
sanitized = sanitized.Replace("<", "<");
sanitized = sanitized.Replace(">", ">");
sanitized = sanitized.Replace("&", "&");
sanitized = sanitized.Replace(""", "\"");
if (!dirty.Equals(sanitized))
{
yield return new ModelValidationResult
{
MemberName = string.Empty,
Message = "A potentially dangerous value was detected from the client."
};
}
}
}
}
示例7: Validate
public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
{
if (metadata.Model is string)
{
return ValidateString((string)metadata.Model, metadata.PropertyName);
}
return Enumerable.Empty<ModelValidationResult>();
}
示例8: GetValidators
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
{
if (IsValidatingProperty(metadata))
{
return GetValidatorsForProperty(metadata, validatorProviders, ValidatorFactory.GetValidator(metadata.ContainerType));
}
return GetValidatorsForModel(
//metadata,
validatorProviders, ValidatorFactory.GetValidator(metadata.ModelType));
}
示例9: GetValidators
/// <summary>
/// Gets the collection of registered <see cref="ModelValidator"/> instances.
/// </summary>
/// <param name="actionContext">The context.</param>
/// <param name="metadata">The metadata.</param>
/// <returns>A collection of registered <see cref="ModelValidator"/> instances.</returns>
public static IEnumerable<ModelValidator> GetValidators(this HttpActionContext actionContext, ModelMetadata metadata)
{
if (actionContext == null)
{
throw Error.ArgumentNull("actionContext");
}
IEnumerable<ModelValidatorProvider> validatorProviders = GetValidatorProviders(actionContext);
return validatorProviders.SelectMany(provider => provider.GetValidators(metadata, validatorProviders));
}
示例10: GetValidators
/// <summary>
/// Gets the validators.
/// </summary>
/// <param name="metadata">The metadata.</param>
/// <param name="validatorProviders">The validator providers.</param>
/// <returns>
/// The validators returned by the default validator providers.
/// </returns>
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
{
var validators = this.defaultModelValidatorProviders.SelectMany(provider => provider.GetValidators(metadata, validatorProviders)).ToList();
foreach (var modelValidator in validators)
{
this.kernel.Inject(modelValidator);
}
return validators;
}
示例11: TypeConversionErrorMessageProvider_DefaultValue
public void TypeConversionErrorMessageProvider_DefaultValue()
{
// Arrange
ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), "SomePropertyName");
// Act
string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(null, metadata, "some incoming value");
// Assert
Assert.Equal("The value 'some incoming value' is not valid for SomePropertyName.", errorString);
}
示例12: GetValidators
/// <summary>
/// Gets a list of validators.
/// </summary>
/// <param name="metadata">The metadata.</param>
/// <param name="actionContext">The context.</param>
/// <param name="attributes">The list of validation attributes.</param>
/// <returns>A list of validators.</returns>
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, HttpActionContext actionContext, IEnumerable<Attribute> attributes)
{
var validators = base.GetValidators(metadata, actionContext, attributes);
foreach (var modelValidator in validators.OfType<DataAnnotationsModelValidator>())
{
var attribute = this.getAttributeMethodInfo.Invoke(modelValidator, new object[0]);
this.kernel.Inject(attribute);
}
return validators;
}
示例13: Validate
public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container) {
if (metadata.Model == null) return Enumerable.Empty<ModelValidationResult>();
var selector = new DefaultValidatorSelector();
var context = new ValidationContext(metadata.Model, new PropertyChain(), selector);
var result = validator.Validate(context);
return !result.IsValid
? ConvertValidationResultToModelValidationResults(result)
: Enumerable.Empty<ModelValidationResult>();
}
示例14: ValueRequiredErrorMessageProvider_DefaultValue
public void ValueRequiredErrorMessageProvider_DefaultValue()
{
// Arrange
ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), "SomePropertyName");
// Act
string errorString = ModelBinderConfig.ValueRequiredErrorMessageProvider(null, metadata, "some incoming value");
// Assert
Assert.Equal("A value is required.", errorString);
}
示例15: GetValidatorsForProperty
private IEnumerable<ModelValidator> GetValidatorsForProperty(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)
{
ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(metadata.ContainerType);
PropertyDescriptor property = typeDescriptor.GetProperties().Find(metadata.PropertyName, true);
if (property == null)
{
throw Error.Argument("metadata", SRResources.Common_PropertyNotFound, metadata.ContainerType, metadata.PropertyName);
}
return GetValidators(metadata, validatorProviders, property.Attributes.OfType<Attribute>());
}