public ObjectResolver(IModelBinder[] binders, IValueConverterRegistry converters, ITypeDescriptorRegistry registry) { _binders.AddRange(binders); var defaultBinder = new StandardModelBinder(converters, registry); _binders.Add(defaultBinder); }
/// <summary> /// Gets the <see cref="ModelBindingContext"/> for this <see cref="HttpActionContext"/>. /// </summary> /// <param name="actionContext">The action context.</param> /// <param name="bindingContext">The binding context.</param> /// <param name="binder">When this method returns, the value associated with the specified binding context, if the context is found; otherwise, the default value for the type of the value parameter.</param> /// <returns><c>true</c> if <see cref="ModelBindingContext"/> was present; otherwise <c>false</c>.</returns> public static bool TryGetBinder(this HttpActionContext actionContext, ModelBindingContext bindingContext, out IModelBinder binder) { if (actionContext == null) { throw Error.ArgumentNull("actionContext"); } if (bindingContext == null) { throw Error.ArgumentNull("bindingContext"); } binder = null; ModelBinderProvider providerFromAttr; if (ModelBindingHelper.TryGetProviderFromAttributes(bindingContext.ModelType, out providerFromAttr)) { binder = providerFromAttr.GetBinder(actionContext, bindingContext); } else { binder = actionContext.ControllerContext.Configuration.Services.GetModelBinderProviders() .Select(p => p.GetBinder(actionContext, bindingContext)) .Where(b => b != null) .FirstOrDefault(); } return binder != null; }
public void CreateModelBinder() { var container = new StructureMapContainer(); IFeature coreServices = new Dolstagis.Web.Lifecycle.CoreServices(); coreServices.ContainerBuilder.SetupApplication(container); binder = container.Get<ModelBinder>(); }
public void ChoseModelBinder(Type modelType, IModelBinder binder) { _report.AddBindingDetail(new ModelBinderSelection{ ModelType = modelType, BinderType = binder.GetType() }); }
/// <summary> /// Register that the given parameter type on an Action is to be bound using the model binder. /// </summary> /// <param name="configuration">configuration to be updated.</param> /// <param name="type">parameter type that binder is applied to</param> /// <param name="binder">a model binder</param> public static void BindParameter(this HttpConfiguration configuration, Type type, IModelBinder binder) { if (configuration == null) { throw Error.ArgumentNull("configuration"); } if (type == null) { throw Error.ArgumentNull("type"); } if (binder == null) { throw Error.ArgumentNull("binder"); } // Add a provider so that we can use this type recursively // Be sure to insert at position 0 to preempt any eager binders (eg, MutableObjectBinder) that // may eagerly claim all types. configuration.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(type, binder)); // Add the binder to the list of rules. // This ensures that the parameter binding will actually use model binding instead of Formatters. // Without this, the parameter binding system may see the parameter type is complex and choose // to use formatters instead, in which case it would ignore the registered model binders. configuration.ParameterBindingRules.Insert(0, type, param => param.BindWithModelBinding(binder)); }
public ElementBinding AddElement(Type elementType, IModelBinder binder) { var binding = new ElementBinding(_elements.Count, elementType, binder); _elements.Add(binding); return binding; }
/// <summary> /// Bind the parameter using the given model binder. /// </summary> /// <param name="parameter">parameter to provide binding for.</param> /// <param name="binder">model binder to use on parameter</param> /// <returns>a binding</returns> public static HttpParameterBinding BindWithModelBinding(this HttpParameterDescriptor parameter, IModelBinder binder) { HttpConfiguration config = parameter.Configuration; IEnumerable<ValueProviderFactory> valueProviderFactories = new ModelBinderAttribute().GetValueProviderFactories(config); return BindWithModelBinding(parameter, binder, valueProviderFactories); }
public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails() { // Arrange var binders = new IModelBinder[] { new TypeConverterModelBinder(), new ComplexModelDtoModelBinder(), new MutableObjectModelBinder() }; var validator = new DataAnnotationsModelValidatorProvider(); var model = new MyModel(); var modelStateDictionary = new ModelStateDictionary(); var values = new Dictionary<string, object> { { "", null } }; var valueProvider = new DictionaryBasedValueProvider(values); // Act var result = await ModelBindingHelper.TryUpdateModelAsync( model, "", Mock.Of<HttpContext>(), modelStateDictionary, new DataAnnotationsModelMetadataProvider(), GetCompositeBinder(binders), valueProvider, new[] { validator }); // Assert Assert.False(result); Assert.Equal("The MyProperty field is required.", modelStateDictionary["MyProperty"].Errors[0].ErrorMessage); }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { // Check for existence of type discriminator field string typeDiscrimKey = CreateSubPropertyName(bindingContext.ModelName, "_TYPEDISC_"); ValueProviderResult vpDiscrim = bindingContext.ValueProvider.GetValue(typeDiscrimKey); if (vpDiscrim != null) { // check for attribute on property specifying the requested type name is allowed string typeName = (string)vpDiscrim.ConvertTo(typeof(string)); var attr = propertyDescriptor.Attributes.OfType<AllowedSubtypesAttribute>().FirstOrDefault(); if (attr != null && attr.AllowedSubtypeNames.Contains(typeName)) { // check if the requested type is different from the property type, but assignable to it Type propType = Type.GetType(typeName); if (propType != propertyDescriptor.PropertyType && propertyDescriptor.PropertyType.IsAssignableFrom(propType)) { // substitute type of property for specified type IModelBinder newPropertyBinder = Binders.GetBinder(propType); var propertyMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, propType); ModelBindingContext newBindingContext = new ModelBindingContext() { ModelMetadata = propertyMetadata, ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, ValueProvider = bindingContext.ValueProvider }; return base.GetPropertyValue(controllerContext, newBindingContext, propertyDescriptor, newPropertyBinder); } } } return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }
public EnumModelBinder(ModelBinderDictionary binders) { if (binders == null) throw new ArgumentNullException("binders"); _defaultBinder = binders.DefaultBinder; binders.DefaultBinder = this; }
/// <summary> /// This method changes de default behavior of a modelbinder when it has to bind a posted photo to the /// Photo property of customer picture. Otherwise it behaves default. /// </summary> /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param> /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param> /// <param name="propertyDescriptor">The descriptor for the property to access. The descriptor provides information such as the component type, property type, and property value. It also provides methods to get or set the property value.</param> /// <param name="propertyBinder">An object that provides a way to bind the property.</param> /// <returns> /// An object that represents the property value. /// </returns> protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { // Check to see if we are binding the Photo Property, otherwise fallback to default behavior if (propertyDescriptor.Name == "Photo") { IValueProvider provider = bindingContext.ValueProvider; // Check if there is a value on the request for the Photo property var result = provider.GetValue(bindingContext.ModelName); // The result should be a posted file HttpPostedFileBase file = result.ConvertTo(typeof(HttpPostedFileBase)) as HttpPostedFileBase; // Check if there's actually a Photo in the request. if (file == (HttpPostedFileBase)null) { //There is no photo. return null; } // Create a byte array with the length of the posted file. byte [] resultValue = new byte[file.ContentLength]; // Read the contents of the posted file to the byte array. file.InputStream.Read(resultValue, 0, file.ContentLength); // Return the byte array. return resultValue; } //If we are binding another property fallback to default behavior. return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }
public void Add(Type modelType, IModelBinder binder) { Precondition.Require(modelType, () => Error.ArgumentNull("modelType")); Precondition.Require(binder, () => Error.ArgumentNull("binder")); _mappings.Add(modelType, binder); }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { var propertyType = propertyDescriptor.PropertyType; // Check if the property type is an enum with the flag attribute if (propertyType.IsEnum && propertyType.GetCustomAttributes(true).Any()) { var providerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (providerValue != null) { var value = providerValue.RawValue; if (value != null) { // In case it is a checkbox list/dropdownlist/radio button list if (value is string[]) { // Create flag value from posted values int flagValue = 0; foreach (string val in ((string[])value)) { flagValue = flagValue | (int)Enum.Parse(propertyType, val); } return Enum.ToObject(propertyType, flagValue); } // In case it is a single value if (value.GetType().IsEnum) { return Enum.ToObject(propertyType, value); } } } } return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }
public RegisterModelBindersTests() { modelBinders = new ModelBinderDictionary(); modelBinder = new FakeModelBinder(); serviceLocator = new Mock<FakeServiceLocator>(); registration = new RegisterModelBinders(modelBinders); }
/// <summary> /// Removes the specified model binder. /// </summary> /// <param name="binder">The model binder to remove.</param> public void Remove(IModelBinder binder) { var pairs = binders.Where(x => x.Value == binder).ToArray(); foreach (var pair in pairs) { binders.Remove(pair.Key); } }
public RegisterDefaultModelBinderStartupTask(IModelBinder modelBinder) { if (modelBinder == null) { throw new ArgumentNullException("modelBinder"); } _modelBinder = modelBinder; }
/// <summary> /// Provides custom logic for creating an <see cref="ISectionID"/> object from a string. /// </summary> /// <param name="controllerContext"></param> /// <param name="bindingContext"></param> /// <param name="propertyDescriptor"></param> /// <param name="propertyBinder"></param> /// <returns></returns> protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { if (propertyDescriptor.PropertyType.IsSubclassOf(typeof(Section))) { return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, new SectionIdModelBinder()); } // TODO: Account for a property that is a collection of ISection objects return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }
public TypeMatchModelBinderProvider(Type type, IModelBinder binder) : base() { Precondition.Require(type, () => Error.ArgumentNull("type")); Precondition.Require(binder, () => Error.ArgumentNull("binder")); _type = type; _binder = binder; }
/// <summary> /// Provides custom logic for creating an <see cref="ISectionID"/> object from a string. /// </summary> /// <param name="controllerContext"></param> /// <param name="bindingContext"></param> /// <param name="propertyDescriptor"></param> /// <param name="propertyBinder"></param> /// <returns></returns> protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { Type propertyType = propertyDescriptor.PropertyType; if (propertyType == typeof(SectionID) || propertyType.IsSubclassOf(typeof(SectionID))) { return SectionID.FromString(bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue); } return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }
protected GenericModelBinderProvider(Type type, IModelBinder binder) { Precondition.Require(type, () => Error.ArgumentNull("type")); Precondition.Require(binder, () => Error.ArgumentNull("binder")); ValidateParameters(type, null); _type = type; _factory = (args) => binder; }
private async Task BindModelAsync(ModelBindingContext bindingContext, IModelBinder binder) { await binder.BindModelAsync(bindingContext); /* bindingContext.Result = await binder.BindModelAsync(bindingContext); var modelBindingResult = result != ModelBindingResult.NoResult ? result : ModelBindingResult.NoResult; return bindingContext;*/ }
public SimpleModelBinderProvider(Type modelType, IModelBinder modelBinder) { if (modelType == null) { throw new ArgumentNullException("modelType"); } if (modelBinder == null) { throw new ArgumentNullException("modelBinder"); } _modelType = modelType; _modelBinderFactory = () => modelBinder; }
public void ProceedAndWarnWithRuntimePolicyOnAndIModelBinder(AlternateType<IModelBinder> alternateModelBinder, IAlternateMethodContext context, Type arg1, IModelBinder returnValue) { context.Setup(c => c.Arguments).Returns(new object[] { arg1 }); context.Setup(c => c.ReturnValue).Returns(returnValue); var sut = new ModelBinderProvider.GetBinder(alternateModelBinder); sut.NewImplementation(context); context.TimerStrategy().Verify(t => t.Time(It.IsAny<Action>())); context.Verify(mb => mb.ReturnValue); }
public void UpdateModelBinders(ModelBinderInspector sut, IInspectorContext context, DummyDefaultModelBinder seedBinder, IModelBinder proxy) { ModelBinders.Binders.Add(typeof(object), seedBinder); context.ProxyFactory.Setup(pf => pf.IsWrapInterfaceEligible<IModelBinder>(It.IsAny<Type>())).Returns(true); context.ProxyFactory.Setup(pf => pf.WrapInterface(It.IsAny<IModelBinder>(), It.IsAny<IEnumerable<IAlternateMethod>>())).Returns(proxy); sut.Setup(context); Assert.Contains(proxy, ModelBinders.Binders.Values); Assert.DoesNotContain(seedBinder, ModelBinders.Binders.Values); context.Logger.Verify(l => l.Info(It.IsAny<string>(), It.IsAny<object[]>())); }
private async Task<ModelBindingResult> BindModelCoreAsync(ModelBindingContext bindingContext, IModelBinder binder) { Debug.Assert(binder != null); var result = await binder.BindModelAsync(bindingContext); var modelBindingResult = result != ModelBindingResult.NoResult ? result : ModelBindingResult.Failed(bindingContext.ModelName); // Were able to resolve a binder type. // Always tell the model binding system to skip other model binders. return modelBindingResult; }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { if (propertyDescriptor.Name == "FirstName") { ValueProviderResult result = bindingContext.ValueProvider.GetValue("FirstName"); string firstName = result.AttemptedValue; return string.Format("{0} Custom", firstName); } //let the default model binder do it's thing return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { if (propertyDescriptor.Name.EqualsOrNullEmpty("Value", StringComparison.CurrentCultureIgnoreCase)) { var value = controllerContext.RequestContext.HttpContext.Request.Unvalidated().Form[bindingContext.ModelName]; var dataTypeModelName = bindingContext.ModelName.Replace("Value", "DataType"); var dataType = (DataType)Enum.Parse(typeof(DataType), bindingContext.ValueProvider.GetValue(dataTypeModelName).AttemptedValue); var parameterValue = DataTypeHelper.ParseValue(dataType, value, false); return parameterValue; } else return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }
public GenericModelBinderProvider(Type modelType, IModelBinder modelBinder) { if (modelType == null) { throw new ArgumentNullException("modelType"); } if (modelBinder == null) { throw new ArgumentNullException("modelBinder"); } ValidateParameters(modelType, null /* modelBinderType */); _modelType = modelType; _modelBinderFactory = _ => modelBinder; }
private void InitFromAttributes() { _binder = GetModelBinder(_parameter); _source = ParameterSource.Default; BindAttribute attribute = (BindAttribute)Attribute.GetCustomAttribute(_parameter, typeof(BindAttribute)); if (attribute != null) { _name = attribute.Name ?? _parameter.Name; _source = ParameterSource.FromString(attribute.Source); _defaultValue = attribute.Default; } }
private static BindResult executeModelBinder(Type type, IModelBinder binder, IBindingContext context) { try { return new BindResult{ Value = binder.Bind(type, context), Problems = context.Problems }; } catch (Exception e) { throw new FubuException(2201, e, "Fatal error while binding model of type {0}. See inner exception", type.AssemblyQualifiedName); } }
public ControllerActionInvoker() { this.ModelBinder = new DefaultModelBinder(); }
public SplitDateTimeModelBinder(IModelBinder fallbackBinder) { this.fallbackBinder = fallbackBinder; }
public static IModelBinder Wrap(this IModelBinder modelBinder) { return(new GlimpseModelBinder(modelBinder)); }
/// <summary> /// Initializes a new instance of the <see cref="ActionInvoker"/> class. /// </summary> /// <param name="controllerBuilder">The controller builder.</param> /// <param name="modelBinder">The model binder.</param> /// <param name="jsonSerializer">The JSON serializer.</param> /// <exception cref="System.ArgumentNullException"> /// </exception> public ActionInvoker(IControllerBuilder controllerBuilder, IModelBinder modelBinder, IJsonSerializer jsonSerializer) { _controllerBuilder = controllerBuilder ?? throw new ArgumentNullException(nameof(controllerBuilder)); _modelBinder = modelBinder ?? throw new ArgumentNullException(nameof(modelBinder)); _jsonSerializer = jsonSerializer ?? throw new ArgumentNullException(nameof(jsonSerializer)); }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { bool sanitize = controllerContext.HttpContext.Request.HttpMethod == "POST"; //get value from default binder object value = base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); if (!sanitize) { return(value); } //sanitize value if it is a string string stringValue = value as string; if (stringValue != null) { return(stringValue.SanitizeString()); } return(value); }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { if (propertyDescriptor.PropertyType.GetInterface(typeof(IEnumerable).Name) != null) { var actualValue = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); if (actualValue != null && !String.IsNullOrWhiteSpace(actualValue.AttemptedValue) && actualValue.AttemptedValue.Contains(",")) { var valueType = propertyDescriptor.PropertyType.GetElementType() ?? propertyDescriptor.PropertyType.GetGenericArguments().FirstOrDefault(); bool isCommaSeparated = propertyDescriptor.Attributes.OfType <CommaSeparatedAttribute>().Any(); if (isCommaSeparated && valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null) { var list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(valueType)); foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' })) { list.Add(Convert.ChangeType(splitValue, valueType)); } if (propertyDescriptor.PropertyType.IsArray) { return(ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list })); } else { return(list); } } } } return(base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder)); }
public ArrayModelBinder(IModelBinder elementBinder) : this(elementBinder, NullLoggerFactory.Instance) { }
private Task <IControllerResponse> MethodNotFoundControllerFunction(IHttpContext context, IModelBinder binder, object controller) { // TODO : MethodNotFound. return(Task.FromResult <IControllerResponse>(new RenderResponse(HttpResponseCode.MethodNotAllowed, new { Message = "Not Allowed" }))); }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { object value = propertyBinder.BindModel(controllerContext, bindingContext); return(value); }
private async Task <ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext, IModelBinder binder) { await binder.BindModelAsync(bindingContext); var modelBindingResult = bindingContext.Result != ModelBindingResult.Failed() ? bindingContext.Result : ModelBindingResult.Failed(); return(modelBindingResult); }
//protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, // PropertyDescriptor propertyDescriptor) //{ // base.BindProperty(controllerContext, bindingContext, propertyDescriptor); //} /// <summary> /// Fix for the default model binder's failure to decode enum types when binding to JSON. /// </summary> protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { var propertyType = propertyDescriptor.PropertyType; if (propertyType.IsEnum) { var providerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (null != providerValue) { var value = providerValue.RawValue; if (null != value) { var valueType = value.GetType(); if (!valueType.IsEnum) { if (valueType == typeof(String)) { switch (((String)value).ToLower()) { case "ddc": value = 0; break; case "rvk": value = 1; break; case "jel": value = 2; break; case "rq": value = 3; break; case "oldrq": value = 4; break; default: value = 5; break; } } return(Enum.ToObject(propertyType, value)); } } } } return(base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder)); }
/// <summary> /// Fix for the default model binder's failure to decode flag enum types from chexbox list. /// </summary> protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { var propertyType = propertyDescriptor.PropertyType; // Check if the property type is an enum with the flag attribute if (propertyType.IsEnum && propertyType.GetCustomAttributes <FlagsAttribute>().Any()) { var providerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (providerValue != null) { var value = providerValue.RawValue; if (value != null) { // In case it is a checkbox list/dropdownlist/radio button list if (value is string[]) { // Create flag value from posted values var flagValue = (( string[] )value).Aggregate(0, (current, v) => current | ( int )Enum.Parse(propertyType, v)); return(Enum.ToObject(propertyType, flagValue)); } // In case it is a single value if (value.GetType().IsEnum) { return(Enum.ToObject(propertyType, value)); } } } } return(base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder)); }
public BodyAndRouteModelBinder(IModelBinder bodyBinder, IModelBinder complexBinder) { _bodyBinder = bodyBinder ?? throw new ArgumentNullException(nameof(bodyBinder)); _complexBinder = complexBinder ?? throw new ArgumentNullException(nameof(complexBinder)); }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { return(BindCsv(propertyDescriptor.PropertyType, propertyDescriptor.Name, bindingContext) ?? base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder)); }
private IModelBinder CreateBinderCore(DefaultModelBinderProviderContext providerContext, object token) { if (!providerContext.Metadata.IsBindingAllowed) { return(NoOpBinder.Instance); } // A non-null token will usually be passed in at the the top level (ParameterDescriptor likely). // This prevents us from treating a parameter the same as a collection-element - which could // happen looking at just model metadata. var key = new Key(providerContext.Metadata, token); // If we're currently recursively building a binder for this type, just return // a PlaceholderBinder. We'll fix it up later to point to the 'real' binder // when the stack unwinds. var stack = providerContext.Stack; for (var i = 0; i < stack.Count; i++) { var entry = stack[i]; if (key.Equals(entry.Key)) { if (entry.Value == null) { // Recursion detected, create a DelegatingBinder. var binder = new PlaceholderBinder(); stack[i] = new KeyValuePair <Key, PlaceholderBinder>(entry.Key, binder); return(binder); } else { return(entry.Value); } } } // OK this isn't a recursive case (yet) so "push" an entry on the stack and then ask the providers // to create the binder. stack.Add(new KeyValuePair <Key, PlaceholderBinder>(key, null)); IModelBinder result = null; for (var i = 0; i < _providers.Length; i++) { var provider = _providers[i]; result = provider.GetBinder(providerContext); if (result != null) { break; } } if (result == null && stack.Count > 1) { // Use a no-op binder if we're below the top level. At the top level, we throw. result = NoOpBinder.Instance; } // "pop" Debug.Assert(stack.Count > 0); var delegatingBinder = stack[stack.Count - 1].Value; stack.RemoveAt(stack.Count - 1); // If the DelegatingBinder was created, then it means we recursed. Hook it up to the 'real' binder. if (delegatingBinder != null) { delegatingBinder.Inner = result; } return(result); }
/// <summary> /// Creates a new <see cref="ArrayModelBinder{TElement}"/>. /// </summary> /// <param name="elementBinder"> /// The <see cref="IModelBinder"/> for binding <typeparamref name="TElement"/>. /// </param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> /// <remarks> /// The binder will not add an error for an unbound top-level model even if /// <see cref="ModelMetadata.IsBindingRequired"/> is <see langword="true"/>. /// </remarks> public ArrayModelBinder(IModelBinder elementBinder, ILoggerFactory loggerFactory) : base(elementBinder, loggerFactory) { }
public KeyValuePairModelBinder(IModelBinder keyBinder, IModelBinder valueBinder) : this(keyBinder, valueBinder, NullLoggerFactory.Instance) { }
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { if (propertyDescriptor.PropertyType.IsSubclassOf(typeof(SystemEntity))) { string id = controllerContext.HttpContext.Request[bindingContext.ModelName + ".Id"]; int idVal; return(int.TryParse(id, out idVal) ? Session.Get(propertyDescriptor.PropertyType, idVal) : null); } object value = base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); return(value); }
private static ModelBindingContext GetBindingContext(IValueProvider valueProvider, IModelBinder innerBinder = null) { var metataProvider = new EmptyModelMetadataProvider(); var bindingContext = new ModelBindingContext { ModelMetadata = metataProvider.GetMetadataForType(null, typeof(KeyValuePair <int, string>)), ModelName = "someName", ValueProvider = valueProvider, ModelBinder = innerBinder ?? CreateIntBinder(), MetadataProvider = metataProvider, ValidatorProvider = Mock.Of <IModelValidatorProvider>() }; return(bindingContext); }
protected virtual object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { object value = propertyBinder.BindModel(controllerContext, bindingContext); if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && Equals(value, String.Empty)) { return(null); } return(value); }
public SanityDocumentModelBinder(IModelBinder inner) { _inner = inner; }
public async Task BindModelAsync(ModelBindingContext bindingContext) { var modelKindName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "file_category"); var modelTypeValue = bindingContext.ValueProvider.GetValue("file_category").FirstValue; IModelBinder modelBinder = null; ModelMetadata modelMetadata = null; string key = bindingContext.ModelName; if (String.IsNullOrEmpty(key)) { key = bindingContext.FieldName; } string val = bindingContext.HttpContext.Request.Form[key]; if (String.IsNullOrEmpty(val)) { val = bindingContext.HttpContext.Request.Query[key]; } if (String.IsNullOrEmpty(val)) { await Task.CompletedTask; } if (bindingContext.ModelType == typeof(string)) { bindingContext.Model = val; } if (bindingContext.ModelType == typeof(int)) { bindingContext.Model = int.Parse(val); } if (bindingContext.ModelType == typeof(long)) { bindingContext.Model = long.Parse(val); } if (bindingContext.ModelType == typeof(float)) { bindingContext.Model = float.Parse(val); } if (bindingContext.ModelType == typeof(double)) { bindingContext.Model = double.Parse(val); } if (bindingContext.ModelType == typeof(short)) { bindingContext.Model = short.Parse(val); } if (bindingContext.ModelType == typeof(DateTime)) { bindingContext.Model = DateTime.Parse(val); } if (bindingContext.Model != null) { bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); } if (bindingContext.ModelType == typeof(IFormFile)) { bindingContext.Model = bindingContext.HttpContext.Request.Form.Files[0]; } var newBindingContext = DefaultModelBindingContext.CreateBindingContext( bindingContext.ActionContext, bindingContext.ValueProvider, modelMetadata, bindingInfo: null, bindingContext.ModelName); await modelBinder.BindModelAsync(newBindingContext); bindingContext.Result = newBindingContext.Result; if (newBindingContext.Result.IsModelSet) { // Setting the ValidationState ensures properties on derived types are correctly bindingContext.ValidationState[newBindingContext.Result] = new ValidationStateEntry { Metadata = modelMetadata, }; } bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); await Task.CompletedTask; }
internal object UpdateDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type keyType, Type valueType) { bool stopOnIndexNotFound; IEnumerable <string> indexes; GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes); IModelBinder keyBinder = Binders.GetBinder(keyType); IModelBinder valueBinder = Binders.GetBinder(valueType); // build up a list of items from the request List <KeyValuePair <object, object> > modelList = new List <KeyValuePair <object, object> >(); foreach (string currentIndex in indexes) { string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex); string keyFieldKey = CreateSubPropertyName(subIndexKey, "key"); string valueFieldKey = CreateSubPropertyName(subIndexKey, "value"); if (!(bindingContext.ValueProvider.ContainsPrefix(keyFieldKey) && bindingContext.ValueProvider.ContainsPrefix(valueFieldKey))) { if (stopOnIndexNotFound) { // we ran out of elements to pull break; } else { continue; } } // bind the key ModelBindingContext keyBindingContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, keyType), ModelName = keyFieldKey, ModelState = bindingContext.ModelState, ValueProvider = bindingContext.ValueProvider }; object thisKey = keyBinder.BindModel(controllerContext, keyBindingContext); // we need to merge model errors up AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, keyFieldKey, keyType, thisKey); if (!keyType.IsInstanceOfType(thisKey)) { // we can't add an invalid key, so just move on continue; } // bind the value modelList.Add(CreateEntryForModel(controllerContext, bindingContext, valueType, valueBinder, valueFieldKey, thisKey)); } // Let's try another method if (modelList.Count == 0) { IEnumerableValueProvider enumerableValueProvider = bindingContext.ValueProvider as IEnumerableValueProvider; if (enumerableValueProvider != null) { IDictionary <string, string> keys = enumerableValueProvider.GetKeysFromPrefix(bindingContext.ModelName); foreach (var thisKey in keys) { modelList.Add(CreateEntryForModel(controllerContext, bindingContext, valueType, valueBinder, thisKey.Value, thisKey.Key)); } } } // if there weren't any elements at all in the request, just return if (modelList.Count == 0) { return(null); } // replace the original collection object dictionary = bindingContext.Model; CollectionHelpers.ReplaceDictionary(keyType, valueType, dictionary, modelList); return(dictionary); }
public FlatFileReader(IModelBinder binder, IServiceLocator services) { _binder = binder; _services = services; }
private static KeyValuePair <object, object> CreateEntryForModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type valueType, IModelBinder valueBinder, string modelName, object modelKey) { ModelBindingContext valueBindingContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, valueType), ModelName = modelName, ModelState = bindingContext.ModelState, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object thisValue = valueBinder.BindModel(controllerContext, valueBindingContext); AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, modelName, valueType, thisValue); return(new KeyValuePair <object, object>(modelKey, thisValue)); }
/// <summary> /// Updates the specified <paramref name="model"/> instance using the specified <paramref name="modelBinder"/> /// and the specified <paramref name="valueProvider"/> and executes validation using the specified /// <paramref name="validatorProvider"/>. /// </summary> /// <param name="model">The model instance to update and validate.</param> /// <param name="modelType">The type of model instance to update and validate.</param> /// <param name="prefix">The prefix to use when looking up values in the <paramref name="valueProvider"/>. /// </param> /// <param name="httpContext">The <see cref="HttpContext"/> for the current executing request.</param> /// <param name="modelState">The <see cref="ModelStateDictionary"/> used for maintaining state and /// results of model-binding validation.</param> /// <param name="metadataProvider">The provider used for reading metadata for the model type.</param> /// <param name="modelBinder">The <see cref="IModelBinder"/> used for binding.</param> /// <param name="valueProvider">The <see cref="IValueProvider"/> used for looking up values.</param> /// <param name="inputFormatters"> /// The set of <see cref="IInputFormatter"/> instances for deserializing the body. /// </param> /// <param name="objectModelValidator">The <see cref="IObjectModelValidator"/> used for validating the /// bound values.</param> /// <param name="validatorProvider">The <see cref="IModelValidatorProvider"/> used for executing validation /// on the model instance.</param> /// <param name="predicate">A predicate which can be used to /// filter properties(for inclusion/exclusion) at runtime.</param> /// <returns>A <see cref="Task"/> that on completion returns <c>true</c> if the update is successful</returns> public static async Task <bool> TryUpdateModelAsync( [NotNull] object model, [NotNull] Type modelType, [NotNull] string prefix, [NotNull] HttpContext httpContext, [NotNull] ModelStateDictionary modelState, [NotNull] IModelMetadataProvider metadataProvider, [NotNull] IModelBinder modelBinder, [NotNull] IValueProvider valueProvider, [NotNull] IList <IInputFormatter> inputFormatters, [NotNull] IObjectModelValidator objectModelValidator, [NotNull] IModelValidatorProvider validatorProvider, [NotNull] Func <ModelBindingContext, string, bool> predicate) { if (!modelType.IsAssignableFrom(model.GetType())) { var message = Resources.FormatModelType_WrongType( model.GetType().FullName, modelType.FullName); throw new ArgumentException(message, nameof(modelType)); } var modelMetadata = metadataProvider.GetMetadataForType(modelType); // Clear ModelStateDictionary entries for the model so that it will be re-validated. ClearValidationStateForModel(modelType, modelState, metadataProvider, prefix); var operationBindingContext = new OperationBindingContext { InputFormatters = inputFormatters, ModelBinder = modelBinder, ValidatorProvider = validatorProvider, MetadataProvider = metadataProvider, HttpContext = httpContext }; var modelBindingContext = new ModelBindingContext { Model = model, ModelMetadata = modelMetadata, ModelName = prefix, ModelState = modelState, ValueProvider = valueProvider, FallbackToEmptyPrefix = true, IsTopLevelObject = true, OperationBindingContext = operationBindingContext, PropertyFilter = predicate, }; var modelBindingResult = await modelBinder.BindModelAsync(modelBindingContext); if (modelBindingResult != null) { var modelExplorer = new ModelExplorer(metadataProvider, modelMetadata, modelBindingResult.Model); var modelValidationContext = new ModelValidationContext(modelBindingContext, modelExplorer); objectModelValidator.Validate( modelValidationContext, new ModelValidationNode(prefix, modelBindingContext.ModelMetadata, modelBindingResult.Model) { ValidateAllProperties = true }); return(modelState.IsValid); } return(false); }
public JimuQueryStringModelBinder(IModelBinder modelBinder) { _modelBinder = modelBinder; }
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { var propertyType = propertyDescriptor.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { var provider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (provider != null && provider.RawValue != null && Type.GetTypeCode(provider.RawValue.GetType()) == TypeCode.Int32) { var value = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(provider.AttemptedValue, bindingContext.ModelMetadata.ModelType); return(value); } } return(base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder)); }
protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { // need to skip properties that aren't part of the request, else we might hit a StackOverflowException string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name); if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey)) { return; } // call into the property's model binder IModelBinder propertyBinder = Binders.GetBinder(propertyDescriptor.PropertyType); object originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model); ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name]; propertyMetadata.Model = originalPropertyValue; ModelBindingContext innerBindingContext = new ModelBindingContext() { ModelMetadata = propertyMetadata, ModelName = fullPropertyKey, ModelState = bindingContext.ModelState, ValueProvider = bindingContext.ValueProvider }; object newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder); propertyMetadata.Model = newPropertyValue; // validation ModelState modelState = bindingContext.ModelState[fullPropertyKey]; if (modelState == null || modelState.Errors.Count == 0) { if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue)) { SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); } } else { SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); // Convert FormatExceptions (type conversion failures) into InvalidValue messages foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList()) { for (Exception exception = error.Exception; exception != null; exception = exception.InnerException) { // We only consider "known" type of exception and do not make too aggressive changes here if (exception is FormatException || exception is OverflowException) { string displayName = propertyMetadata.GetDisplayName(); string errorMessageTemplate = GetValueInvalidResource(controllerContext); string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName); modelState.Errors.Remove(error); modelState.Errors.Add(errorMessage); break; } } } } }