public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext.Request.Method == HttpMethod.Get || actionContext.Request.Method == HttpMethod.Delete) { await BindFromUri(metadataProvider, actionContext, cancellationToken); } else { await BindFromBody(metadataProvider, actionContext, cancellationToken); } }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { List <MediaTypeFormatter> perRequestFormatters = new List <MediaTypeFormatter>(); MediaTypeFormatter perRequestFormatter = _formatter.GetPerRequestFormatterInstance(Descriptor.ParameterType, actionContext.Request, actionContext.Request.Content.Headers.ContentType); perRequestFormatters.Add(perRequestFormatter); HttpParameterBinding innerBinding = CreateInnerBinding(perRequestFormatters); return(innerBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken)); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext.Request.Content != null && actionContext.Request.Content.Headers.ContentLength > 0) { // [FromBody]读取信息 return(_defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken)); } else { // [FromUri]读取信息 return(_defaultUriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken)); } }
bool IBodyModelValidator.Validate(object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, string keyPrefix) { var customizations = actionContext.ActionDescriptor.GetParameters().Where(x => x.ParameterName == keyPrefix) .Select(x => x.GetCustomAttributes <CustomizeValidatorAttribute>().FirstOrDefault()) .FirstOrDefault(); if (customizations != null) { actionContext.Request.Properties["_FV_Customizations"] = customizations; } return(base.Validate(model, type, metadataProvider, actionContext, keyPrefix)); }
static void Main(string[] args) { HttpConfiguration configuration = new HttpConfiguration(); ModelMetadataProvider metadataProvider = configuration.Services.GetModelMetadataProvider(); ModelMetadata metadata = metadataProvider.GetMetadataForProperty(null, typeof(Employee), "Salary"); IEnumerable <ModelValidatorProvider> validatorProviders = configuration.Services.GetModelValidatorProviders(); ModelValidator[] validators = metadata.GetValidators(validatorProviders).ToArray(); for (int i = 0; i < validators.Length; i++) { Console.WriteLine("{0}.{1}", i + 1, validators[i].GetType().Name); } }
public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { await formatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); var employee = GetValue(actionContext) as Employee; await modelBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); var employeeFromUri = GetValue(actionContext) as Employee; employee = Merge(employee, employeeFromUri); SetValue(actionContext, employee); }
public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (_willReadBody) { await actionContext.Request.ReadFormDataAsync(this.Descriptor.Configuration, cancellationToken); } var model = GetObjectValue(actionContext); SetValue(actionContext, model); _validator?.Validate(model, this.Descriptor.ParameterType, metadataProvider, actionContext, this.Descriptor.ParameterName); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (_injectionPoint != null) { var resolver = actionContext.Request.GetDependencyScope() as ICormoDependencyResolver; if (resolver != null) { var resolved = resolver.GetReference(_injectionPoint); actionContext.ActionArguments[Descriptor.ParameterName] = resolved; } } return(Task.FromResult(0)); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext.Request.Content != null && actionContext.Request.Content.Headers.ContentLength > 0) { // we have something from the body, try that first return(_defaultFormatterBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken)); } else { // we need to read things from uri return(_defaultUriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken)); } }
// Execute the binding for the given request. // On success, this will add the parameter to the actionContext.ActionArguments dictionary. // Caller ensures IsError==false. public override Task ExecuteBindingAsync( ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken ) { string name = Descriptor.ParameterName; HttpRequestMessage request = actionContext.ControllerContext.Request; actionContext.ActionArguments.Add(name, request); return(TaskHelpers.Completed()); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { string name = Descriptor.ParameterName; ModelBindingContext ctx = GetModelBindingContext(metadataProvider, actionContext); bool haveResult = _binder.BindModel(actionContext, ctx); object model = haveResult ? ctx.Model : Descriptor.DefaultValue; SetValue(actionContext, model); return(TaskHelpers.Completed()); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext == null) { throw Error.ArgumentNull("actionContext"); } HttpRequestMessage request = actionContext.Request; if (request == null) { throw Error.Argument("actionContext", SRResources.ActionContextMustHaveRequest); } HttpActionDescriptor actionDescriptor = actionContext.ActionDescriptor; if (actionDescriptor == null) { throw Error.Argument("actionContext", SRResources.ActionContextMustHaveDescriptor); } HttpConfiguration configuration = request.GetConfiguration(); if (configuration == null) { throw Error.Argument("actionContext", SRResources.RequestMustContainConfiguration); } // Get the entity type from the parameter type if it is ODataQueryOptions<T>. // Fall back to the return type if not. Also, note that the entity type from the return type and ODataQueryOptions<T> // can be different (example implementing $select or $expand). Type entityClrType = GetEntityClrTypeFromParameterType(Descriptor) ?? GetEntityClrTypeFromActionReturnType(actionDescriptor); IEdmModel model = request.ODataProperties().Model ?? actionDescriptor.GetEdmModel(entityClrType); ODataQueryContext entitySetContext = new ODataQueryContext( model, entityClrType, request.ODataProperties().Path); Func <ODataQueryContext, HttpRequestMessage, ODataQueryOptions> createODataQueryOptions = (Func <ODataQueryContext, HttpRequestMessage, ODataQueryOptions>)Descriptor.Properties.GetOrAdd(CreateODataQueryOptionsCtorKey, _ => { return(Delegate.CreateDelegate(typeof(Func <ODataQueryContext, HttpRequestMessage, ODataQueryOptions>), _createODataQueryOptions.MakeGenericMethod(entityClrType))); }); ODataQueryOptions parameterValue = createODataQueryOptions(entitySetContext, request); SetValue(actionContext, parameterValue); return(TaskHelpers.Completed()); }
// Perf-sensitive - keeping the async method as small as possible private async Task ExecuteBindingAsyncCore(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, HttpParameterDescriptor paramFromBody, Type type, HttpRequestMessage request, IFormatterLogger formatterLogger, CancellationToken cancellationToken) { var model = await ReadContentAsync(request, type, Formatters, formatterLogger, cancellationToken); if (model == null) { model = System.Activator.CreateInstance(type); } ; var routeParams = actionContext.ControllerContext.RouteData.Values; foreach (var key in routeParams.Keys.Where(k => k != "controller")) { var prop = type.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if (prop == null) { continue; } var descriptor = TypeDescriptor.GetConverter(prop.PropertyType); if (descriptor.CanConvertFrom(typeof(string))) { prop.SetValue(model, descriptor.ConvertFromString(routeParams[key] as string)); } } var queryParams = actionContext.Request.GetQueryNameValuePairs(); foreach (var queryParam in queryParams) { var prop = type.GetProperty(queryParam.Key, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if (prop == null) { continue; } var descriptor = TypeDescriptor.GetConverter(prop.PropertyType); if (descriptor.CanConvertFrom(typeof(string))) { prop.SetValue(model, descriptor.ConvertFromString(queryParam.Value)); } } // Set the merged model in the context SetValue(actionContext, model); if (BodyModelValidator != null) { BodyModelValidator.Validate(model, type, metadataProvider, actionContext, paramFromBody.ParameterName); } }
/// <summary> /// Parses the parameter value from the request body. /// </summary> /// <param name="metadataProvider"></param> /// <param name="actionContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { // read request body (query string or JSON) var parameters = ParseParametersFromBody(actionContext.Request, actionContext); if (parameters != null) { // 从路由中获取参数及值,全部添加进入BODY中取得的参数列表中 // 如果路由参数与BODY参数有重复,将只保留路由参数 foreach (var routeParam in actionContext.ControllerContext.RouteData.Values) { parameters.Remove(routeParam.Key); parameters.Add(routeParam.Key, routeParam.Value.ToString()); } } if (parameters != null) { object paramValue; if (Descriptor.ParameterType == typeof(string)) { paramValue = parameters.FirstOrDefault().Value; } else if (Descriptor.ParameterType.IsEnum) { paramValue = Enum.Parse(Descriptor.ParameterType, parameters.FirstOrDefault().Value.ToString()); } else if (Descriptor.ParameterType.IsPrimitive || Descriptor.ParameterType.IsValueType) { // TODO: Are these conditions ok? I'd rather not have to check that the type implements IConvertible. paramValue = Convert.ChangeType(parameters.FirstOrDefault().Value, Descriptor.ParameterType); } else { var jsonSerializerSettings = actionContext.ControllerContext.Configuration.Formatters.JsonFormatter.SerializerSettings; //将完整的参数字典类型,转化为JSON字符串 string stringValue = JsonConvert.SerializeObject(parameters, jsonSerializerSettings); // when deserializing an object, pass in the global settings so that custom converters, etc. are honored paramValue = JsonConvert.DeserializeObject(stringValue, Descriptor.ParameterType, jsonSerializerSettings); } // Set the binding result here SetValue(actionContext, paramValue); } // now, we can return a completed task with no result TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(); tcs.SetResult(default(object)); return(tcs.Task); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { IEnumerable <string> values; if (actionContext.Request.Headers.TryGetValues(this.name, out values)) { actionContext.ActionArguments[this.Descriptor.ParameterName] = values.FirstOrDefault(); } var taskSource = new TaskCompletionSource <object>(); taskSource.SetResult(null); return(taskSource.Task); }
private async Task BindFromUri(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { var uriBinding = _descriptor.BindWithAttribute(new FromUriAttribute()); await uriBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); var bindedValue = GetValue(actionContext) as IClientQuery; var query = GetValue(actionContext) as IClientQuery ?? Activator.CreateInstance(_descriptor.ParameterType) as IClientQuery; if (bindedValue == null) { SetValue(actionContext, query); } var clientFilterable = query as IClientFilterable; var clientSortable = query as IClientSortable; var clientPageable = query as IClientPageable; var queryString = actionContext.Request.GetQueryNameValuePairs() .Where(x => Keys.KnownKeys.Contains(x.Key)) .ToDictionary(x => x.Key, x => (object)x.Value); var routeDataValues = actionContext.Request.GetRouteData() .Values .Where(x => Keys.KnownKeys.Contains(x.Key)); var requestValues = queryString.Union(routeDataValues).ToDictionary(x => x.Key, x => x.Value); if (queryString.ContainsKey(Keys.Filter) && clientFilterable != null) { var converter = new QueryStringFilterConverter(); var filter = (IFilter)converter.ConvertFrom(queryString[Keys.Filter]); clientFilterable.ClientFilter = filter ?? new AlwaysTrueFilter(); } if (queryString.ContainsKey(Keys.Sort) && clientSortable != null) { var converter = new SortTypeConverter(); var sort = (ISort)converter.ConvertFrom(queryString[Keys.Sort]); clientSortable.ClientSort = sort ?? clientSortable.ClientSort ?? new RandomSort(); } if ((queryString.ContainsKey(Keys.PageNumber) || queryString.ContainsKey(Keys.PageSize)) && clientPageable != null) { int pageNumber = 1, pageSize = 10; var hasNumber = requestValues.ContainsKey(Keys.PageNumber) && int.TryParse(requestValues[Keys.PageNumber].ToString(), out pageNumber); var hasSize = requestValues.ContainsKey(Keys.PageSize) && int.TryParse(requestValues[Keys.PageSize].ToString(), out pageSize); var page = new ClientPage { PageNumber = hasNumber ? (int?)pageNumber : null, PageSize = hasSize ? (int?)pageSize : null }; clientPageable.ClientPage = page; } }
internal static MvcLabel BeginLabel( this HtmlHelper html, string expression, string labelText, object htmlAttributes, ModelMetadataProvider metadataProvider) { return(BeginLabel( html, expression, labelText, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), metadataProvider)); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { IValueProvider valueProvider = factory.GetValueProvider(actionContext); if (valueProvider != null) { ValueProviderResult result = valueProvider.GetValue(Descriptor.ParameterName); if (result != null) { SetValue(actionContext, result.RawValue); } } return(Task.FromResult <object>(null)); }
internal static MvcLabel BeginLabelFor <TModel, TValue>( this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, string labelText, object htmlAttributes, ModelMetadataProvider metadataProvider) { return(BeginLabelFor( html, expression, labelText, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), metadataProvider)); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { IEnumerable <string> headerValues; if (actionContext.Request.Headers.TryGetValues(_headerName, out headerValues)) { actionContext.ActionArguments[Descriptor.ParameterName] = headerValues.Select(_valueConverter).FirstOrDefault(); } else { actionContext.ActionArguments[Descriptor.ParameterName] = _getDefaultValue(); } return(Task.FromResult(0)); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { var productRawString = actionContext.Request.Headers.GetValues(Descriptor.ParameterName).FirstOrDefault(); Product product; if (Product.TryParse(productRawString, out product)) { actionContext.ActionArguments[Descriptor.ParameterName] = product; } Debugger.Break(); return(Task.FromResult(0)); }
private ContentModelMetadata GetContentContentTypeFullNameModelMetadata(ModelMetadataProvider provider, Type containerType, ContentType contentType = null, Func <object> modelAccessor = null) { if (modelAccessor == null) { modelAccessor = () => contentType.FullName; } var modelMetadata = new ContentModelMetadata(provider, containerType, modelAccessor, typeof(string), "ContentTypeFullName"); modelMetadata.TemplateHint = "HiddenInput"; modelMetadata.HideSurroundingHtml = true; return(modelMetadata); }
private ContentModelMetadata GetContentCultureModelMetadata(ModelMetadataProvider provider, Type containerType, object container = null, Func <object> modelAccessor = null) { if (modelAccessor == null) { modelAccessor = () => _cultureManager.GetDefaultCulture(); } var modelMetadata = new ContentModelMetadata(provider, containerType, modelAccessor, typeof(CultureInfo), "Culture"); modelMetadata.TemplateHint = "HiddenInput"; modelMetadata.HideSurroundingHtml = true; return(modelMetadata); }
public MetadataOverrideScope(ModelMetadata metadata) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (metadata.ModelType == null) { throw new ArgumentException("Need ModelType", "metadata"); } _oldMetadataProvider = ModelMetadataProviders.Current; _metadata = metadata; _modelType = metadata.ModelType; // Mock a ModelMetadataProvider which delegates to the old one in most cases. No need to special-case // GetMetadataForProperties() because product code uses it only within ModelMetadata.Properties and our // metadata instance will call _oldMetadataProvider there. var metadataProvider = new Mock <ModelMetadataProvider>(); metadataProvider .Setup(p => p.GetMetadataForProperties(It.IsAny <object>(), It.IsAny <Type>())) .Returns((object container, Type containerType) => _oldMetadataProvider.GetMetadataForProperties(container, containerType)); metadataProvider .Setup(p => p.GetMetadataForType(It.IsAny <Func <object> >(), It.IsAny <Type>())) .Returns((Func <object> modelAccessor, Type modelType) => _oldMetadataProvider.GetMetadataForType(modelAccessor, modelType)); // When metadata for _modelType is requested, then return a clone of the provided metadata instance. // GetMetadataForProperty() is important because the static discovery methods (e.g. // ModelMetadata.FromLambdaExpression) use it. metadataProvider .Setup(p => p.GetMetadataForType(It.IsAny <Func <object> >(), _modelType)) .Returns((Func <object> modelAccessor, Type modelType) => GetMetadataForType(modelAccessor, modelType)); metadataProvider .Setup(p => p.GetMetadataForProperty(It.IsAny <Func <object> >(), It.IsAny <Type>(), It.IsAny <string>())) .Returns((Func <object> modelAccessor, Type containerType, string propertyName) => GetMetadataForProperty(modelAccessor, containerType, propertyName)); // Calls to GetMetadataForProperties for the modelType are incorrect because _metadata.Provider must // reference _oldMetadataProvider and not this mock. metadataProvider .Setup(p => p.GetMetadataForProperty(It.IsAny <Func <object> >(), _modelType, It.IsAny <string>())) .Throws <InvalidOperationException>(); // Finally make our ModelMetadataProvider visible everywhere. ModelMetadataProviders.Current = metadataProvider.Object; }
public ModelValidationRequiredMemberSelector(ModelMetadataProvider metadataProvider, IEnumerable <ModelValidatorProvider> validatorProviders) { if (metadataProvider == null) { throw Error.ArgumentNull("metadataProvider"); } if (validatorProviders == null) { throw Error.ArgumentNull("validatorProviders"); } _metadataProvider = metadataProvider; _validatorProviders = validatorProviders.ToList(); }
public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { string name = ""; if (metadata.ContainerType != null && this.OtherPropertyDisplayName == null) { CompareAttribute displayName = this; ModelMetadataProvider current = ModelMetadataProviders.Current; name = current.GetMetadataForProperty(() => metadata.Model, metadata.ContainerType, this.OtherProperty).GetDisplayName(); } ILocalizationService _LocalizationService = DependencyResolver.Current.GetService <ILocalizationService>(); yield return(new ModelClientValidationEqualToRule(String.Format(CultureInfo.CurrentCulture, _LocalizationService.LocalizeString(ErrorMessageString, CultureInfo.CurrentCulture.Name), name, OtherPropertyDisplayName ?? OtherProperty), FormatPropertyForClientValidation(this.OtherProperty))); }
/// <summary> /// Executes the binding asynchronous. /// </summary> /// <param name="metadataProvider">The metadata provider.</param> /// <param name="actionContext">The action context.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>System.Threading.Tasks.Task.</returns> public override async Task ExecuteBindingAsync( ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { PatchRequestBase model = await CreatePatchRequest(actionContext.Request, Descriptor.Configuration); SetValue(actionContext, model); if (_BodyModelValidator != null) { _BodyModelValidator.Validate(model, Descriptor.ParameterType, metadataProvider, actionContext, Descriptor.ParameterName); } }
private async Task BindFromBody(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { var bodyBinding = _descriptor.BindWithAttribute(new FromBodyAttribute()); var memoryStream = new MemoryStream(); await actionContext.Request.Content.CopyToAsync(memoryStream); memoryStream.Position = 0; var content = new StreamContent(memoryStream); actionContext.Request.Content.Headers.AsEnumerable().ToList().ForEach(x => content.Headers.TryAddWithoutValidation(x.Key, x.Value)); actionContext.Request.Content = new StreamContent(memoryStream); await bodyBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken); var query = GetValue(actionContext) as IClientQuery; if (query == null) { SetValue(actionContext, null); return; } var clientFilterable = query as IClientFilterable; var clientSortable = query as IClientSortable; var clientPageable = query as IClientPageable; memoryStream.Position = 0; var apiQuery = await content.ReadAsAsync(typeof(ApiQuery), actionContext.ControllerContext.Configuration.Formatters, cancellationToken) as ApiQuery; if (apiQuery == null) { return; } if (clientFilterable != null && apiQuery.Filter != null && !(apiQuery.Filter is AlwaysTrueFilter)) { clientFilterable.ClientFilter = apiQuery.Filter; } if (clientSortable != null && apiQuery.Sort != null && !(apiQuery.Sort is RandomSort)) { clientSortable.ClientSort = apiQuery.Sort; } if (clientPageable != null && (apiQuery.PageSize != null && apiQuery.PageNumber != null)) { clientPageable.ClientPage = new ClientPage { PageNumber = apiQuery.PageNumber, PageSize = apiQuery.PageSize }; } SetValue(actionContext, query); }
public MetadataOverrideScope(ModelMetadata metadata) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (metadata.ModelType == null) { throw new ArgumentException("Need ModelType", "metadata"); } _oldMetadataProvider = ModelMetadataProviders.Current; _metadata = metadata; _modelType = metadata.ModelType; // Mock a ModelMetadataProvider which delegates to the old one in most cases. No need to special-case // GetMetadataForProperties() because product code uses it only within ModelMetadata.Properties and our // metadata instance will call _oldMetadataProvider there. var metadataProvider = new Mock<ModelMetadataProvider>(); metadataProvider .Setup(p => p.GetMetadataForProperties(It.IsAny<object>(), It.IsAny<Type>())) .Returns((object container, Type containerType) => _oldMetadataProvider.GetMetadataForProperties(container, containerType)); metadataProvider .Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>())) .Returns((Func<object> modelAccessor, Type modelType) => _oldMetadataProvider.GetMetadataForType(modelAccessor, modelType)); // When metadata for _modelType is requested, then return a clone of the provided metadata instance. // GetMetadataForProperty() is important because the static discovery methods (e.g. // ModelMetadata.FromLambdaExpression) use it. metadataProvider .Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), _modelType)) .Returns((Func<object> modelAccessor, Type modelType) => GetMetadataForType(modelAccessor, modelType)); metadataProvider .Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>())) .Returns((Func<object> modelAccessor, Type containerType, string propertyName) => GetMetadataForProperty(modelAccessor, containerType, propertyName)); // Calls to GetMetadataForProperties for the modelType are incorrect because _metadata.Provider must // reference _oldMetadataProvider and not this mock. metadataProvider .Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), _modelType, It.IsAny<string>())) .Throws<InvalidOperationException>(); // Finally make our ModelMetadataProvider visible everywhere. ModelMetadataProviders.Current = metadataProvider.Object; }
public override Task ExecuteBindingAsync( ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { // It is safe to assume that the Shipment instance exists // inside the HttpRequestMessage.Properties dictionary // because we woulnd't be here if it doesn't. var shipment = actionContext.Request .Properties[ShipmentDictionaryKey] as Shipment; actionContext.ActionArguments.Add(_parameterName, shipment); return(Task.FromResult(0)); }
public void ModelMetadataProvidersCurrentDelegatesToResolver() { // Arrange Mock <ModelMetadataProvider> provider = new Mock <ModelMetadataProvider>(); Resolver <ModelMetadataProvider> resolver = new Resolver <ModelMetadataProvider> { Current = provider.Object }; ModelMetadataProviders providers = new ModelMetadataProviders(resolver); // Act ModelMetadataProvider result = providers.CurrentInternal; // Assert Assert.Same(provider.Object, result); }
public void Initialialize() { metadataProvider = new Mock<ModelMetadataProvider>(); metadata = new Mock<ModelMetadata>(metadataProvider.Object, null, null, typeof(object), null); viewData = new ViewDataDictionary(); viewContext = new Mock<ViewContext>(); viewContext.Expect(c => c.ViewData).Returns(viewData); viewDataContainer = new Mock<IViewDataContainer>(); viewDataContainer.Expect(c => c.ViewData).Returns(viewData); html = new HtmlHelper<object>(viewContext.Object, viewDataContainer.Object); metadataProvider.Expect(p => p.GetMetadataForProperties(It.IsAny<object>(), It.IsAny<Type>())) .Returns(new ModelMetadata[0]); metadataProvider.Expect(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>())) .Returns(metadata.Object); metadataProvider.Expect(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>())) .Returns(metadata.Object); originalProvider = ModelMetadataProviders.Current; ModelMetadataProviders.Current = metadataProvider.Object; }
internal ModelMetadataProviders() { currentProvider = new PocoMetadataProvider(); }
/// <summary> /// Initializes a new instance of the <see cref="ExtendedModelMetadata"/> class. /// </summary> /// <param name="provider">The provider.</param> /// <param name="containerType">Type of the container.</param> /// <param name="modelAccessor">The model accessor.</param> /// <param name="modelType">Type of the model.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="metadata">The metadata.</param> public ExtendedModelMetadata(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName, ModelMetadataItemBase metadata) : base(provider, containerType, modelAccessor, modelType, propertyName) { Metadata = metadata; }
internal ModelMetadataProviders() { _currentProvider = new DataAnnotationsModelMetadataProvider(); }