Ejemplo n.º 1
0
        /// <inheritdoc />
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // This method is optimized to use cached tasks when possible and avoid allocating
            // using Task.FromResult or async state machines.

            var modelType = bindingContext.ModelType;

            if (modelType != typeof(IFormFile) && !typeof(IEnumerable <IFormFile>).IsAssignableFrom(modelType))
            {
                // Not a type this model binder supports. Let other binders run.
                return(TaskCache.CompletedTask);
            }

            var createFileCollection = modelType == typeof(IFormFileCollection) &&
                                       !bindingContext.ModelMetadata.IsReadOnly;

            if (!createFileCollection && !ModelBindingHelper.CanGetCompatibleCollection <IFormFile>(bindingContext))
            {
                // Silently fail and stop other model binders running if unable to create an instance or use the
                // current instance.
                bindingContext.Result = ModelBindingResult.Failed(bindingContext.ModelName);
                return(TaskCache.CompletedTask);
            }

            ICollection <IFormFile> postedFiles;

            if (createFileCollection)
            {
                postedFiles = new List <IFormFile>();
            }
            else
            {
                postedFiles = ModelBindingHelper.GetCompatibleCollection <IFormFile>(bindingContext);
            }

            return(BindModelCoreAsync(bindingContext, postedFiles));
        }
Ejemplo n.º 2
0
        private static object GetCompatibleCollection(ModelBindingContext bindingContext, string[] values)
        {
            // Almost-always success if IsTopLevelObject.
            if (!bindingContext.IsTopLevelObject && values.Length == 0)
            {
                return(null);
            }

            if (bindingContext.ModelType.IsAssignableFrom(typeof(string[])))
            {
                // Array we already have is compatible.
                return(values);
            }

            var collection = ModelBindingHelper.GetCompatibleCollection <string>(bindingContext, values.Length);

            for (int i = 0; i < values.Length; i++)
            {
                collection.Add(values[i]);
            }

            return(collection);
        }