示例#1
0
    /// <summary>
    /// Sets the value for the <see cref="ModelStateEntry"/> with the specified <paramref name="key"/>.
    /// </summary>
    /// <param name="key">The key for the <see cref="ModelStateEntry"/> entry</param>
    /// <param name="valueProviderResult">
    /// A <see cref="ValueProviderResult"/> with data for the <see cref="ModelStateEntry"/> entry.
    /// </param>
    public void SetModelValue(string key, ValueProviderResult valueProviderResult)
    {
        if (key == null)
        {
            throw new ArgumentNullException(nameof(key));
        }

        // Avoid creating a new array for rawValue if there's only one value.
        object?rawValue;

        if (valueProviderResult == ValueProviderResult.None)
        {
            rawValue = null;
        }
        else if (valueProviderResult.Length == 1)
        {
            rawValue = valueProviderResult.Values[0];
        }
        else
        {
            rawValue = valueProviderResult.Values.ToArray();
        }

        SetModelValue(key, rawValue, valueProviderResult.ToString());
    }
        protected override void CheckModel(
            ModelBindingContext bindingContext,
            ValueProviderResult valueProviderResult,
            object model)
        {
            if (bindingContext.ModelMetadata.IsFlagsEnum && valueProviderResult.Length > 1)
            {
                try
                {
                    // The base model binder knows how to convert an array of enum values...

                    var allValues = valueProviderResult.Values;
                    var converter = TypeDescriptor.GetConverter(_modelType);

                    var converted = allValues
                                    .Select(v => converter.ConvertFrom(
                                                context: null,
                                                culture: valueProviderResult.Culture,
                                                value: v))
                                    .Cast <int>();

                    var allValuesAreDefined = converted.All(v => Enum.IsDefined(_modelType, v));
                    if (allValuesAreDefined)
                    {
                        model = Enum.ToObject(_modelType, converted.Sum());
                        bindingContext.Result = ModelBindingResult.Success(model);
                    }
                    else
                    {
                        bindingContext.ModelState.TryAddModelError(
                            bindingContext.ModelName,
                            bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(
                                valueProviderResult.ToString()));
                    }
                }
                catch (Exception exception)
                {
                    var isFormatException = exception is FormatException;
                    if (!isFormatException && exception.InnerException != null)
                    {
                        // TypeConverter throws System.Exception wrapping the FormatException,
                        // so we capture the inner exception.
                        exception = ExceptionDispatchInfo.Capture(exception.InnerException).SourceException;
                    }

                    bindingContext.ModelState.TryAddModelError(
                        bindingContext.ModelName,
                        exception,
                        bindingContext.ModelMetadata);
                }
            }
            else
            {
                base.CheckModel(bindingContext, valueProviderResult, model);
            }
        }
 protected void CheckModel(ModelBindingContext bindingContext, ValueProviderResult valueProviderResult, object model)
 {
     // When converting newModel a null value may indicate a failed conversion for an otherwise required
     // model (can't set a ValueType to null). This detects if a null model value is acceptable given the
     // current bindingContext. If not, an error is logged.
     if (model == null && !bindingContext.ModelMetadata.IsReferenceOrNullableType)
     {
         bindingContext.ModelState.TryAddModelError(
             bindingContext.ModelName,
             bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(
                 valueProviderResult.ToString()));
     }
     else
     {
         bindingContext.Result = ModelBindingResult.Success(model);
     }
 }
 protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
 {
     if (propertyDescriptor.PropertyType == typeof(TagList))
     {
         ValueProviderResult value   = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
         string[]            rawTags = value.ToString().Split(',');
         TagList             tags    = new TagList();
         foreach (string rawTag in rawTags)
         {
             // for numbers - get them from DB
             // for strings - create new and store in DB
             // then add them to tags
         }
         propertyDescriptor.SetValue(bindingContext.Model, tags);
     }
     else
     {
         base.BindProperty(controllerContext, bindingContext, propertyDescriptor)
     }
 }
 protected override void CheckModel(
     ModelBindingContext bindingContext,
     ValueProviderResult valueProviderResult,
     object?model)
 {
     if (model == null)
     {
         base.CheckModel(bindingContext, valueProviderResult, model);
     }
     else if (IsDefinedInEnum(model, bindingContext))
     {
         bindingContext.Result = ModelBindingResult.Success(model);
     }
     else
     {
         bindingContext.ModelState.TryAddModelError(
             bindingContext.ModelName,
             bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(
                 valueProviderResult.ToString()));
     }
 }
示例#6
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            string modelName = bindingContext.ModelName;
            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                // no entry
                return(Task.CompletedTask);
            }

            ModelStateDictionary modelState = bindingContext.ModelState;

            modelState.SetModelValue(modelName, valueProviderResult);

            ModelMetadata metadata = bindingContext.ModelMetadata;
            Type          type     = metadata.UnderlyingOrModelType;

            string      value   = valueProviderResult.FirstValue;
            CultureInfo culture = valueProviderResult.Culture;

            object?model;

            if (string.IsNullOrWhiteSpace(value))
            {
                model = null;
            }
            else if (type == typeof(byte[]))
            {
                if (value.StartsWith(Prefix))
                {
                    model = Bytes.FromHexString(value);
                }
                else
                {
                    throw new FormatException("Byte value must start with '0x'");
                }
            }
            else
            {
                // unreachable
                throw new NotSupportedException();
            }

            // When converting value, a null model may indicate a failed conversion for an otherwise required
            // model (can't set a ValueType to null). This detects if a null model value is acceptable given the
            // current bindingContext. If not, an error is logged.
            if (model == null && !metadata.IsReferenceOrNullableType)
            {
                modelState.TryAddModelError(
                    modelName,
                    metadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(
                        valueProviderResult.ToString()));
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Success(model);
            }

            return(Task.CompletedTask);
        }
示例#7
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }
            ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            try
            {
                JObject obj = new JObject();
                if (bindingContext.ModelType == typeof(JObject))
                {
                    foreach (var item in bindingContext.ActionContext.HttpContext.Request.Form)
                    {
                        obj.Add(new JProperty(item.Key.ToString(), item.Value.ToString()));
                    }
                    if ((obj.Count == 0))
                    {
                        bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(result.ToString()));
                        return(Task.CompletedTask);
                    }
                    bindingContext.Result = (ModelBindingResult.Success(obj));
                    return(Task.CompletedTask);
                }
                return(Task.CompletedTask);
            }
            catch (Exception exception)
            {
                if (!(exception is FormatException) && (exception.InnerException != null))
                {
                    exception = ExceptionDispatchInfo.Capture(exception.InnerException).SourceException;
                }
                bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, exception, bindingContext.ModelMetadata);
                return(Task.CompletedTask);
            }
        }
示例#8
0
            public Task BuilderUploadModel(ModelBindingContext bindingContext)
            {
                ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

                if (bindingContext.HttpContext.Request.Form.Files.Count > 0)
                {
                    JObject cusobj = new JObject();
                    foreach (var key in bindingContext.HttpContext.Request.Form.Keys)
                    {
                        cusobj.Add(key, bindingContext.HttpContext.Request.Form[key].ToString());
                    }
                    var file     = bindingContext.HttpContext.Request.Form.Files[0];
                    var fileName = file.FileName.Substring(file.FileName.LastIndexOf(@"\") + 1);
                    bindingContext.Result = (ModelBindingResult.Success(new UploadModel
                    {
                        FileName = fileName.Substring(0, fileName.LastIndexOf(".")),
                        Length = file.Length,
                        FileStream = file.OpenReadStream(),
                        CustomData = cusobj,
                        Extension = fileName?.Substring(fileName.LastIndexOf("."))
                    }));
                    return(Task.CompletedTask);
                }
                else
                {
                    bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(result.ToString()));
                    return(Task.CompletedTask);
                }
            }
示例#9
0
        /// <summary>
        /// BindModelAsync
        /// </summary>
        /// <param name="bindingContext">bindingContext</param>
        /// <returns>Task</returns>
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }
            ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);//调用取值 ValueProvider

            try
            {
                if (bindingContext.ModelType == typeof(JObject))
                {
                    JObject obj = new JObject();
                    if (bindingContext.ActionContext.HttpContext.Request.ContentType == "application/json") //json
                    {
                        if (result.ToString().StartsWith("["))                                              //是否是组?
                        {
                            obj = (JObject)JArray.Parse(result.ToString()).First;                           //取首值。
                            bindingContext.Result = (ModelBindingResult.Success(obj));
                            return(Task.CompletedTask);
                        }
                        else
                        {
                            obj = JObject.Parse(result.ToString());//不是组直接取值
                        }
                    }
                    else  //form
                    {
                        foreach (var item in bindingContext.ActionContext.HttpContext.Request.Form)
                        {
                            obj.Add(new JProperty(item.Key, item.Value.ToString()));
                        }
                    }
                    if ((obj.Count == 0))
                    {
                        bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(result.ToString()));
                        return(Task.CompletedTask);
                    }
                    bindingContext.Result = (ModelBindingResult.Success(obj));
                    return(Task.CompletedTask);
                }
                if (bindingContext.ModelType == typeof(JArray))
                {
                    JArray obj = new JArray();
                    if (bindingContext.ActionContext.HttpContext.Request.ContentType.
                        StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) //json
                    {
                        if (result.ToString().StartsWith("["))                              //是否是组?
                        {
                            var array = JArray.Parse(result.ToString());
                            bindingContext.Result = (ModelBindingResult.Success(array));
                            return(Task.CompletedTask);
                        }
                    }
                    if ((obj.Count == 0))
                    {
                        bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueMustNotBeNullAccessor(result.ToString()));
                        return(Task.CompletedTask);
                    }
                    bindingContext.Result = (ModelBindingResult.Success(obj));
                    return(Task.CompletedTask);
                }
                return(Task.CompletedTask);
            }
            catch (Exception exception)
            {
                if (!(exception is FormatException) && (exception.InnerException != null))
                {
                    exception = ExceptionDispatchInfo.Capture(exception.InnerException).SourceException;
                }
                bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, exception, bindingContext.ModelMetadata);
                return(Task.CompletedTask);
            }
        }