public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            var valueAsString = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(valueAsString))
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            var result = DateTime.Parse(valueAsString, new CultureInfo("th-TH"));

            bindingContext.Result = ModelBindingResult.Success(result);
            return(Task.CompletedTask);
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            var valueAsString = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(valueAsString))
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            string[] latLongStr = valueAsString.Split(',');

            Point result = GeographyExtensions.CreatePoint(double.Parse(latLongStr[0]), double.Parse(latLongStr[1]));

            bindingContext.Result = ModelBindingResult.Success(result);

            return(Task.CompletedTask);
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult != ValueProviderResult.None)
            {
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                var valueAsString = valueProviderResult.FirstValue;
                if (string.IsNullOrWhiteSpace(valueAsString))
                {
                    return(_fallbackBinder.BindModelAsync(bindingContext));
                }

                var model = valueAsString.ApplyCorrectYeKe();
                bindingContext.Result = ModelBindingResult.Success(model);
                return(Task.CompletedTask);
            }

            return(_fallbackBinder.BindModelAsync(bindingContext));
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            var valueAsString = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(valueAsString))
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            DbGeography result = null;

            string[] latLongStr = valueAsString.Split(',');
            string   point      = string.Format("POINT ({0} {1})", latLongStr[1], latLongStr[0]);

            //4326 format puts LONGITUDE first then LATITUDE
            result = DbGeography.FromText(point, 4326);

            bindingContext.Result = ModelBindingResult.Success(result);

            return(Task.CompletedTask);
        }
Exemplo n.º 5
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            var valueAsString = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(valueAsString))
            {
                return(_fallbackBinder.BindModelAsync(bindingContext));
            }

            var dataString        = bindingContext.HttpContext.GetJsonDataFromQueryString();
            var dataSourceRequest = JsonConvert.DeserializeObject <DataSourceRequest>(dataString);

            bindingContext.Result = ModelBindingResult.Success(dataSourceRequest);

            return(Task.CompletedTask);
        }
        public Task BindModelAsync(ModelBindingContext model_binding_context)
        {
            if (model_binding_context == null)
            {
                throw new ArgumentNullException(nameof(model_binding_context));
            }

            FieldName = model_binding_context.FieldName;

            PartValues = model_binding_context.ValueProvider.GetValue(FieldName);

            if (PartValues == ValueProviderResult.None)
            {
                return(FallbackModelBinder.BindModelAsync(model_binding_context));
            }

            FieldValueAsString = FieldValueAsNormalString = PartValues.FirstValue;

            ////////////////////////////////////////////////////
            // если строка содержит десятичный/дробный разделитель -> строка дополняется нулями с обоих сторон.
            // Таким образом исключаем точки в начале или в конце строки:
            // ".5" -> "0.50"
            // "5." -> "05.0"
            if (FloatSeparator.IsMatch(FieldValueAsNormalString))
            {
                FieldValueAsNormalString = "0" + FieldValueAsNormalString + "0";
            }

            ////////////////////////////////////////////////////
            // заменим дробный разделитель на текущий системный
            FieldValueAsNormalString = FloatSeparator.Replace(FieldValueAsNormalString, CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

            ////////////////////////////////////////////////////
            // если не корректная строка -> передаём привязку системному привязчику
            if (!FloatPattern.IsMatch(FieldValueAsNormalString))
            {
                return(FallbackModelBinder.BindModelAsync(model_binding_context));
            }

            if (model_binding_context.ModelMetadata.ModelType == typeof(double))
            {
                model_binding_context.Result = ModelBindingResult.Success(GetDoubleFromString);
            }
            else if (model_binding_context.ModelMetadata.ModelType == typeof(float))
            {
                model_binding_context.Result = ModelBindingResult.Success(GetFloatFromString);
            }
            else if (model_binding_context.ModelMetadata.ModelType == typeof(decimal))
            {
                model_binding_context.Result = ModelBindingResult.Success(GetDecimalFromString);
            }
            else
            {
                return(FallbackModelBinder.BindModelAsync(model_binding_context));
            }

            return(Task.CompletedTask);
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var datePartValues = bindingContext.ValueProvider.GetValue("Date");
            var timePartValues = bindingContext.ValueProvider.GetValue("Time");

            if (datePartValues == ValueProviderResult.None || timePartValues == ValueProviderResult.None)
            {
                return(fallbackBinder.BindModelAsync(bindingContext));
            }

            string date = datePartValues.FirstValue;
            string time = timePartValues.FirstValue;

            DateTime.TryParse(date, out DateTime parsedDateValue);
            DateTime.TryParse(time, out DateTime parsedTimeValue);

            var result = new DateTime(parsedDateValue.Year,
                                      parsedDateValue.Month,
                                      parsedDateValue.Day,
                                      parsedTimeValue.Hour,
                                      parsedTimeValue.Minute,
                                      parsedTimeValue.Second);

            bindingContext.Result = ModelBindingResult.Success(result);
            return(Task.CompletedTask);
        }
Exemplo n.º 8
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult.FirstValue is string str &&
                !string.IsNullOrEmpty(str))
            {
                if (bindingContext.ModelName == "Id" || bindingContext.ModelName == "Password")
                {
                    bindingContext.Result = ModelBindingResult.Success(str);
                }
                else
                {
                    bindingContext.Result = ModelBindingResult.Success(str.Trim());
                }
                return(Task.CompletedTask);
            }

            return(FallbackBinder.BindModelAsync(bindingContext));
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult != ValueProviderResult.None)
            {
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                var valueAsString = valueProviderResult.FirstValue;


                DateTime dateTime;
                string   format = "dd.MM.yyyy";

                if (valueAsString.Length >= 12 && valueAsString.Contains(":"))
                {
                    format = "dd.MM.yyyy HH:mm";
                }

                if (DateTime.TryParseExact(valueAsString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
                {
                    bindingContext.Result = ModelBindingResult.Success(dateTime);
                }
                else
                {
                    bindingContext.Result = ModelBindingResult.Success(null);
                }

                return(Task.CompletedTask);
            }

            return(baseBinder.BindModelAsync(bindingContext));
        }
Exemplo n.º 10
0
            public async Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }

                var fieldName = nameof(Model.Value);
                var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
                ModelBindingResult valueResult;

                using (bindingContext.EnterNestedScope(
                           bindingContext.ModelMetadata.Properties[fieldName],
                           fieldName,
                           modelName,
                           model: null))
                {
                    await _binder.BindModelAsync(bindingContext);

                    valueResult = bindingContext.Result;
                }

                if (!valueResult.IsModelSet)
                {
                    return;
                }

                var model = new Model
                {
                    FieldName = bindingContext.FieldName,
                    Value     = (string)valueResult.Model,
                };

                bindingContext.Result = ModelBindingResult.Success(model);
            }
Exemplo n.º 11
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            Type fctype, fitype, fdtype; string index;

            fctype = getTransformation(bindingContext, out fitype, out fdtype, out index);
            if (fctype == null)
            {
                return(inner.BindModelAsync(bindingContext));
            }
            if (fitype == null)
            {
                fitype = fctype;
                fctype = null;
            }
            return(innerBinding(bindingContext, fctype, fdtype, fitype, index));
        }
Exemplo n.º 12
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult != null && valueProviderResult.FirstValue is string str && !string.IsNullOrEmpty(str))
            {
                //Strip out xml tags, prevent XPath / XML injection attacks
                if ((str.Contains("<")) || (str.Contains(">")))
                {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Invalid character");
                }

                //Trim off spaces
                str = str.Trim();

                bindingContext.Result = ModelBindingResult.Success(str);
                return(Task.CompletedTask);
            }

            return(FallbackBinder.BindModelAsync(bindingContext));
        }
Exemplo n.º 13
0
        internal async Task <ModelBindingResult> TryBindStrongModel <TModel>(
            ModelBindingContext bindingContext,
            IModelBinder binder,
            string propertyName)
        {
            var propertyModelMetadata = bindingContext.ModelMetadata.Properties[propertyName];
            var propertyModelName     = ModelNames.CreatePropertyModelName(bindingContext.ModelName, propertyName);

            using (bindingContext.EnterNestedScope(
                       modelMetadata: propertyModelMetadata,
                       fieldName: propertyName,
                       modelName: propertyModelName,
                       model: null))
            {
                await binder.BindModelAsync(bindingContext);

                var result = bindingContext.Result;
                if (result != null && result.Value.IsModelSet)
                {
                    return(result.Value);
                }
                else
                {
                    return(ModelBindingResult.Failed(propertyModelName));
                }
            }
        }
Exemplo n.º 14
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            await _bodyBinder.BindModelAsync(bindingContext);

            if (bindingContext.Result.IsModelSet)
            {
                bindingContext.Model = bindingContext.Result.Model;
            }

            await _complexBinder.BindModelAsync(bindingContext);

            var modelType     = bindingContext.ModelMetadata.UnderlyingOrModelType;
            var modelInstance = bindingContext.Result.Model;

            foreach (var routParam in bindingContext.ActionContext.RouteData.Values)
            {
                var paramValue = routParam.Value as string;

                if (Guid.TryParse(paramValue, out var paramGuidValue))
                {
                    var idProperty = modelType.GetProperties()
                                     .FirstOrDefault(p => p.Name.Equals(routParam.Key, StringComparison.InvariantCultureIgnoreCase));

                    if (idProperty != null)
                    {
                        idProperty.ForceSetValue(modelInstance, paramGuidValue);
                    }
                }
            }

            bindingContext.Result = ModelBindingResult.Success(modelInstance);
        }
        /// <inheritdoc />
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // Try to get the XElement.
            ModelBindingResult result;
            var xElementMetadata = bindingContext.ModelMetadata.GetMetadataForType(typeof(XElement));

            using (var innerContext = bindingContext.EnterNestedScope(
                       xElementMetadata,
                       bindingContext.FieldName,
                       bindingContext.ModelName,
                       bindingContext.Model))
            {
                await _bodyModelBinder.BindModelAsync(bindingContext);

                result = bindingContext.Result;
            }

            // If we got the XElement, create the SalesforceNotifications instance and return that.
            if (result.IsModelSet)
            {
                result = ModelBindingResult.Success(new SalesforceNotifications((XElement)result.Model));
            }

            bindingContext.Result = result;
        }
Exemplo n.º 16
0
        public Task InvokeAsync()
        {
            using (_logger.BeginScope("consumer invoker begin"))
            {
                _logger.LogDebug("Executing consumer Topic: {0}", _consumerContext.ConsumerDescriptor.MethodInfo.Name);

                var obj = ActivatorUtilities.GetServiceOrCreateInstance(_serviceProvider,
                                                                        _consumerContext.ConsumerDescriptor.ImplTypeInfo.AsType());

                var value = _consumerContext.DeliverMessage.Content;

                if (_executor.MethodParameters.Length > 0)
                {
                    var firstParameter = _executor.MethodParameters[0];

                    var bindingContext = ModelBindingContext.CreateBindingContext(value,
                                                                                  firstParameter.Name, firstParameter.ParameterType);

                    _modelBinder.BindModelAsync(bindingContext);
                    _executor.Execute(obj, bindingContext.Result);
                }
                else
                {
                    _executor.Execute(obj);
                }
                return(Task.CompletedTask);
            }
        }
Exemplo n.º 17
0
        private async ValueTask <ModelBindingResult> BindParameterAsync(
            ModelBindingContext bindingContext,
            ModelMetadata parameter,
            IModelBinder parameterBinder,
            string fieldName,
            string modelName)
        {
            Debug.Assert(parameter.MetadataKind == ModelMetadataKind.Parameter);

            ModelBindingResult result;

            using (bindingContext.EnterNestedScope(
                       modelMetadata: parameter,
                       fieldName: fieldName,
                       modelName: modelName,
                       model: null))
            {
                await parameterBinder.BindModelAsync(bindingContext);

                result = bindingContext.Result;
            }

            if (!result.IsModelSet && parameter.IsBindingRequired)
            {
                var message = parameter.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(fieldName);
                bindingContext.ModelState.TryAddModelError(modelName, message);
            }

            return(result);
        }
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (!int.TryParse(bindingContext.ValueProvider.GetValue("id").FirstValue, out int productId))
            {
                throw new Exception("The product id was not provided");
            }

            var editModel = new ProductConfigurationEditModel
            {
                Fields = productRepository.GetProductFields(productId)
            };

            for (int i = 0; i < editModel.Fields.Count; i++)
            {
                BaseField     field         = editModel.Fields[i];
                ModelMetadata modelMetadata = modelMetadataProvider.GetMetadataForType(field.GetType());
                IModelBinder  modelBinder   = modelBinderFactory.CreateBinder(new ModelBinderFactoryContext
                {
                    Metadata   = modelMetadata,
                    CacheToken = modelMetadata
                });

                string modelName = $"{bindingContext.BinderModelName}.Fields[{i}]".TrimStart('.');
                using (var scope = bindingContext.EnterNestedScope(modelMetadata, modelName, modelName, field))
                {
                    await modelBinder.BindModelAsync(bindingContext);
                }
            }

            bindingContext.Result = ModelBindingResult.Success(editModel);
        }
Exemplo n.º 19
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult != ValueProviderResult.None)
            {
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                var valueAsString = valueProviderResult.FirstValue;

                if (decimal.TryParse(valueAsString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
                                     CultureInfo.InvariantCulture, out var result))
                {
                    bindingContext.Result = ModelBindingResult.Success(result);

                    return(Task.CompletedTask);
                }
            }

            return(_modelBinder.BindModelAsync(bindingContext));
        }
Exemplo n.º 20
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            // в случае ошибки возвращаем исключение
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // с помощью поставщика значений получаем данные из запроса
            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // если не найдено значений с данными ключами, вызываем привязчик модели по умолчанию
            if (value == ValueProviderResult.None)
            {
                return(m_fallbackBinder.BindModelAsync(bindingContext));
            }

            string valueAttempted = value.FirstValue;

            if (string.IsNullOrWhiteSpace(valueAttempted))
            {
                bindingContext.Result = ModelBindingResult.Success(null);
                return(Task.CompletedTask);
            }

            // устанавливаем результат привязки
            bindingContext.Result = ModelBindingResult.Success(valueAttempted.Trim());
            return(Task.CompletedTask);
        }
Exemplo n.º 21
0
        async Task ResolveParam(ModelBindingContext bindingContext)
        {
            var    httpCtx = bindingContext.HttpContext;
            var    req     = bindingContext.HttpContext.Request;
            object res;

            if (req.Method == "POST")
            {
                //on post
                if (req.ContentType.Contains("application/json"))
                {
                    res = ResolveFromPostJsonBody(bindingContext);
                }
                else if (req.HasFormContentType)
                {
                    //Use default model binder for forms data.
                    await _defaultModelBinder.BindModelAsync(bindingContext);

                    return;
                }
                else
                {
                    throw new Exception($"Unsapported http post content-type.");
                }
            }
            else
            {
                throw new Exception($"Unsapported request method. Supported only GET and POST.");
            }

            bindingContext.Result = ModelBindingResult.Success(res);
        }
Exemplo n.º 22
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var modelname           = bindingContext.ModelType.Name;

            if (bindingContext.ActionContext.HttpContext.Request.Path.HasValue)
            {
                string currMethod = bindingContext.ActionContext.HttpContext.Request.Method;

                if ("POST".Equals(currMethod) || "PUT".Equals(currMethod))
                {
                    dynamic model      = null;
                    string  bodyAsText = new StreamReader(bindingContext.HttpContext.Request.Body).ReadToEndAsync().Result;

                    if (modelname == "RegisterDto")
                    {
                        model = JsonConvert.DeserializeObject <RegisterDto>(bodyAsText);
                    }
                    bindingContext.Result = ModelBindingResult.Success(model);
                }
            }
            return(_fallbackBinder.BindModelAsync(bindingContext));
        }
Exemplo n.º 23
0
        /// <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="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] 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
            {
                ModelBinder       = modelBinder,
                ValidatorProvider = validatorProvider,
                MetadataProvider  = metadataProvider,
                HttpContext       = httpContext
            };

            var modelBindingContext = new ModelBindingContext
            {
                Model                   = model,
                ModelMetadata           = modelMetadata,
                ModelName               = prefix,
                ModelState              = modelState,
                ValueProvider           = valueProvider,
                FallbackToEmptyPrefix   = 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);
                modelValidationContext.RootPrefix = prefix;
                objectModelValidator.Validate(modelValidationContext);
                return(modelState.IsValid);
            }

            return(false);
        }
Exemplo n.º 24
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var model = modelActivator.CreateInstance(configuration);

            if (model == null)
            {
                await fallbackModelBinder.BindModelAsync(bindingContext);

                return;
            }

            modelPropertyActivator.Activate(configuration, model);
            bindingContext.Model = model;
            await fallbackModelBinder.BindModelAsync(bindingContext);

            modelCache.Put(bindingContext.Model);
        }
Exemplo n.º 25
0
        public static async Task <ModelBindingResult> BindModelResultAsync(
            this IModelBinder binder,
            ModelBindingContext context)
        {
            await binder.BindModelAsync(context);

            return(context.Result ?? default(ModelBindingResult));
        }
        /// <summary>
        /// Reads the JSON HTTP request entity body.
        /// </summary>
        /// <param name="context">The <see cref="ResourceExecutingContext"/>.</param>
        /// <returns>
        /// A <see cref="Task"/> that on completion provides a <see cref="JObject"/> containing the HTTP request entity
        /// body.
        /// </returns>
        protected virtual async Task <JObject> ReadAsJsonAsync(ResourceExecutingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;

            if (request.Body == null ||
                !request.ContentLength.HasValue ||
                request.ContentLength.Value == 0L ||
                !HttpMethods.IsPost(request.Method))
            {
                // Other filters will log and return errors about these conditions.
                return(null);
            }

            var modelState    = context.ModelState;
            var actionContext = new ActionContext(
                context.HttpContext,
                context.RouteData,
                context.ActionDescriptor,
                modelState);

            var valueProviderFactories = context.ValueProviderFactories;
            var valueProvider          = await CompositeValueProvider.CreateAsync(actionContext, valueProviderFactories);

            var bindingContext = DefaultModelBindingContext.CreateBindingContext(
                actionContext,
                valueProvider,
                _jObjectMetadata,
                bindingInfo: null,
                modelName: WebHookConstants.ModelStateBodyModelName);

            // Read request body.
            try
            {
                await _bodyModelBinder.BindModelAsync(bindingContext);
            }
            finally
            {
                request.Body.Seek(0L, SeekOrigin.Begin);
            }

            if (!bindingContext.ModelState.IsValid)
            {
                return(null);
            }

            if (!bindingContext.Result.IsModelSet)
            {
                throw new InvalidOperationException(Resources.VerifyNotification_ModelBindingFailed);
            }

            // Success
            return((JObject)bindingContext.Result.Model);
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == ValueProviderResult.None)
            {
                return(_inner.BindModelAsync(bindingContext));
            }

            if (bindingContext.ActionContext.RouteData.Values.TryGetValue(value.FirstValue, out object model) &&
                model is ISanityDocument)
            {
                bindingContext.Result = ModelBindingResult.Success(model);
                return(Task.CompletedTask);
            }

            return(_inner.BindModelAsync(bindingContext));
        }
Exemplo n.º 28
0
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            await _binder.BindModelAsync(bindingContext);

            if (bindingContext.Result.IsModelSet)
            {
                bindingContext.Result = ModelBindingResult.Success(ModelSanitizer.Sanitize(bindingContext.Result.Model));
            }
        }
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            await _decoratedBinder.BindModelAsync(bindingContext);

            if (bindingContext.Result.Model is IUserContextCommand command)
            {
                command.AuthenticatedUserId = Guid.Empty;
            }
        }
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            await _binder.BindModelAsync(bindingContext);

            if (bindingContext.Result.IsModelSet)
            {
                Model.Verify(bindingContext.Result.Model);
            }
        }
Exemplo n.º 31
0
        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;*/
        }
Exemplo n.º 32
0
        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;
        }