public bool BindModel(HttpActionContext actionContext,
                          System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(TestRequest))
        {
            return(false);
        }
        bindingContext.Model = new TestRequest();

        var parameters = actionContext.Request.RequestUri.ParseQueryString();

        typeof(TestRequest)
        .GetProperties()
        .Select(property => property.Name)
        .ToList()
        .ForEach(propertyName =>
        {
            var parameterValue = parameters[propertyName];

            if (parameterValue == null)
            {
                return;
            }
            typeof(TestRequest).GetProperty(propertyName).SetValue(bindingContext.Model, parameterValue);
        });

        return(bindingContext.ModelState.IsValid);
    }
        private bool TryBindFromRouteData(
            HttpActionContext actionContext,
            ModelBindingContext bindingContext,
            out PayloadResult result)
        {
            var values = actionContext.ControllerContext.RouteData.Values
                         .Where(x => !x.Key.ContainsAny(new[] { "action", "id", "controller" })).ToList();

            if (!values.Any())
            {
                result = null;
                return(false);
            }

            result = new PayloadResult();
            foreach (var value in actionContext.ControllerContext.RouteData.Values.Where(
                         x => !x.Key.ContainsAny(new[] { "action", "id", "controller" })))
            {
                var    json = value.Value as string;
                object jsonObject;
                result.Values.Add(
                    value.Key,
                    json.TryDeserializeObject(SerializerSettings, out jsonObject) ? jsonObject : value.Value);
            }

            return(true);
        }
Example #3
0
        //for web api
        public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            DateTime dt;
            var      value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (DateTime.TryParseExact(value.AttemptedValue, _dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
            {
                bindingContext.Model = dt;
                return(true);
            }

            if (DateTime.TryParseExact(value.AttemptedValue, _dateOnlyFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
            {
                bindingContext.Model = dt;
                return(true);
            }

            if (DateTime.TryParseExact(value.AttemptedValue, _timeOnlyFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
            {
                bindingContext.Model = dt;
                return(true);
            }

            return(false);
        }
Example #4
0
        public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null)
            {
                return(false);
            }
            var date = value.AttemptedValue;

            if (String.IsNullOrEmpty(date))
            {
                return(false);
            }

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));
            try
            {
                bindingContext.Model = DateTime.Parse(date);
                return(true);
            }
            catch (Exception)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));
                return(false);
            }
        }
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        string val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        bindingContext.Model = val;
        return(true);
    }
Example #6
0
        /// <inheritdoc/>
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            try
            {
                object payload;
                if (TryBindFromRouteData(actionContext, bindingContext, out payload))
                {
                    bindingContext.Model = payload;
                    return(true);
                }

                if (TryBindFromJson(actionContext, bindingContext, out payload))
                {
                    bindingContext.Model = payload;
                    return(true);
                }

                return(false);
            }
            catch (Exception exception)
            {
                bindingContext.ModelState.AddModelError("PayloadResultDeserializationException", exception);

                return(false);
            }
        }
        public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(bool) && bindingContext.ModelType != typeof(bool?))
            {
                return(false);
            }

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

            if (input != null && !string.IsNullOrEmpty(input.AttemptedValue))
            {
                bool result;
                if (input.AttemptedValue == "1" || input.AttemptedValue == "true")
                {
                    bindingContext.Model = true;
                    return(true);
                }
                if (!bool.TryParse(input.AttemptedValue, out result))
                {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, "是无效的bool值");
                    return(false);
                }
            }

            return(true);
        }
        private IDictionary <string, object> Parser(HttpActionContext arg1,
                                                    System.Web.Http.ModelBinding.ModelBindingContext modelBindingContext)
        {
            var model = new DataTableAdditionalParametersModel();

            Type type = model.GetType();

            PropertyInfo[] properties = type.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                var value = modelBindingContext.ValueProvider.GetValue(property.Name.ToLowerInvariant());
                if (value != null)
                {
                    if (property.PropertyType.Name == typeof(Severity).Name)
                    {
                        //var inst = Activator.CreateInstance(property.PropertyType, value.AttemptedValue);
                        property.SetValue(model, value.AttemptedValue);
                    }
                    else
                    {
                        property.SetValue(model, value.AttemptedValue);
                    }
                }
            }
            return(model.ToDictionary());

            return(null);
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            //NOTE: Validation is done in the filter
            if (actionContext.Request.Content.IsMimeMultipartContent() == false)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = IOHelper.MapPath("~/App_Data/TEMP/FileUploads");

            //ensure it exists
            Directory.CreateDirectory(root);
            var provider = new MultipartFormDataStreamProvider(root);

            var task = Task.Run(() => GetModelAsync(actionContext, bindingContext, provider))
                       .ContinueWith(x =>
            {
                if (x.IsFaulted && x.Exception != null)
                {
                    throw x.Exception;
                }

                //now that everything is binded, validate the properties
                var contentItemValidator = GetValidationHelper();
                contentItemValidator.ValidateItem(actionContext, x.Result);

                bindingContext.Model = x.Result;
            });

            task.Wait();

            return(bindingContext.Model != null);
        }
Example #10
0
        public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            var queryString = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);

            bindingContext.Model = BuildModel(queryString);

            return(true);
        }
Example #11
0
        public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            bindingContext.Model = bindingContext.ValueProvider
                                   .GetValue(bindingContext.ModelName)
                                   .ConvertTo(bindingContext.ModelType, Thread.CurrentThread.CurrentCulture);

            bindingContext.ValidationNode.ValidateAllProperties = true;

            return(true);
        }
Example #12
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///     A System.Web.Http.ModelBinding.ModelBindingContext extension method that gets value or
        ///     default.
        /// </summary>
        ///
        /// <remarks>
        ///     LM ANWAR, 5/1/2013.
        /// </remarks>
        ///
        /// <param name="modelBindingContext">
        ///     Context for the model binding.
        /// </param>
        /// <param name="key">
        ///     The key of the value object to retrieve.
        /// </param>
        ///
        /// <returns>
        ///     The value or default.
        /// </returns>
        ///-------------------------------------------------------------------------------------------------

        public static string GetValueOrDefault(this System.Web.Http.ModelBinding.ModelBindingContext modelBindingContext, string key)
        {
            var result = modelBindingContext.ValueProvider.GetValue(key);

            if (result != null)
            {
                return(Convert.ToString(result.RawValue));
            }

            return(string.Empty);
        }
Example #13
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Retrieves a value object using the specified key.
        /// </summary>
        ///
        /// <remarks>
        ///     LM ANWAR, 5/1/2013.
        /// </remarks>
        ///
        /// <typeparam name="T">
        ///     Generic type parameter.
        /// </typeparam>
        /// <param name="modelBindingContext">
        ///     Context for the model binding.
        /// </param>
        /// <param name="key">
        ///     The key of the value object to retrieve.
        /// </param>
        ///
        /// <returns>
        ///     The value object for the specified key.
        /// </returns>
        ///-------------------------------------------------------------------------------------------------

        public static T GetValueOrDefault <T>(this System.Web.Http.ModelBinding.ModelBindingContext modelBindingContext, string key) where T : struct
        {
            var result = modelBindingContext.ValueProvider.GetValue(key);

            if (result != null)
            {
                return((T)Convert.ChangeType(result.RawValue, typeof(T)));
            }

            return(default(T));
        }
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        // transform to upper-case
        var transformedValue = val.AttemptedValue.ToUpperInvariant();

        bindingContext.Model = transformedValue;

        return(true);
    }
Example #15
0
        private bool TryBindFromJson(HttpActionContext actionContext, ModelBindingContext bindingContext, out object result)
        {
            var json = actionContext.Request.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            if (json.TryDeserializeObject(bindingContext.ModelType, SerializerSettings, out result))
            {
                return(true);
            }

            result = null;
            return(false);
        }
Example #16
0
 public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
 {
     if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null)
     {
         var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
         bindingContext.Model = long.TryParse(val, out var newValue) ? newValue : long.MinValue;
     }
     else
     {
         bindingContext.Model = long.MinValue;
     }
     return(true);
 }
Example #17
0
 // get processing value
 private T?GetValue <T>(System.Web.Http.ModelBinding.ModelBindingContext bindingContext, string key) where T : struct
 {
     System.Web.Http.ValueProviders.ValueProviderResult valueResult;
     valueResult = bindingContext.ValueProvider.GetValue(key);
     if (valueResult == null)
     {
         return(null);
     }
     else
     {
         return((T?)valueResult.ConvertTo(typeof(T)));
     }
 }
Example #18
0
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        var vpr = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (vpr != null)
        {
            //parameter has been passed
            //preserve its value!
            //(if empty string, leave it as it is, instead of setting null)
            bindingContext.Model = vpr.AttemptedValue;
        }
        return(true);
    }
Example #19
0
 public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
 {
     if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null)
     {
         var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
         bindingContext.Model = val;
     }
     else
     {
         bindingContext.Model = string.Empty;
     }
     return(true);
 }
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        var        posted  = actionContext.Request.Content.ReadAsStringAsync().Result;
        AddressDTO address = JsonConvert.DeserializeObject <AddressDTO>(posted);

        if (address != null)
        {
            // moar val here
            bindingContext.Model = address;
            return(true);
        }
        return(false);
    }
Example #21
0
        /// <summary>
        /// WEB API version
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext,
                              System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            var info = new Models.EnvironmentInfo();

            info.RequestedUrl = actionContext.Request.RequestUri.ToString();
            info.UserId       = GetLoggedUser();

            // you also can get form/request properties

            bindingContext.Model = info;

            return(true);
        }
Example #22
0
        private bool TryBindFromRouteData(HttpActionContext actionContext, ModelBindingContext bindingContext, out object result)
        {
            var values = actionContext.ControllerContext.RouteData.Values.Where(x => !x.Key.ContainsAny(new[] { "action", "id", "controller" })).ToList();

            if (!values.Any())
            {
                result = null;
                return(false);
            }

            if (!string.IsNullOrEmpty(bindingContext.ModelName) && actionContext.ControllerContext.RouteData.Values.ContainsKey(bindingContext.ModelName))
            {
                var singleValue = actionContext.ControllerContext.RouteData.Values[bindingContext.ModelName];
                if (bindingContext.ModelType.IsInstanceOfType(singleValue))
                {
                    result = singleValue;
                    return(true);
                }

                var singleValueString = singleValue as string;
                if (singleValueString != null && singleValueString.TryDeserializeObject(bindingContext.ModelType, SerializerSettings, out result))
                {
                    return(true);
                }
            }

            Dictionary <string, object> routeValues = new Dictionary <string, object>();

            foreach (var value in actionContext.ControllerContext.RouteData.Values.Where(x => !x.Key.ContainsAny(new[] { "action", "id", "controller" })))
            {
                var    json = value.Value as string;
                object jsonObject;
                routeValues.Add(
                    value.Key,
                    json.TryDeserializeObject(SerializerSettings, out jsonObject) ? jsonObject : value.Value);
            }

            var jsonString = JsonConvert.SerializeObject(routeValues, SerializerSettings);

            if (jsonString.TryDeserializeObject(bindingContext.ModelType, SerializerSettings, out result))
            {
                return(true);
            }

            result = null;
            return(false);
        }
Example #23
0
 public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
 {
     if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null)
     {
         var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
         if (string.IsNullOrEmpty(val))
         {
             val = "0";
         }
         bindingContext.Model = decimal.TryParse(val, out var newValue) ? newValue : decimal.MinValue;
     }
     else
     {
         bindingContext.Model = decimal.MinValue;
     }
     return(true);
 }
Example #24
0
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(DateTime?))
        {
            return(false);
        }

        long result;

        if (!long.TryParse(actionContext.RequestContext.RouteData.Values["from"].ToString(), out result))
        {
            return(false);
        }

        bindingContext.Model = new DateTime(result);

        return(bindingContext.ModelState.IsValid);
    }
Example #25
0
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(DateTime?))
        {
            return(false);
        }

        long result;

        if (!long.TryParse(actionContext.Request.RequestUri.Segments.Last(), out result))
        {
            return(false);
        }

        bindingContext.Model = new DateTime(result);

        return(bindingContext.ModelState.IsValid);
    }
Example #26
0
        public bool BindModel(
            WebApi.Controllers.HttpActionContext actionContext,
            WebApi.ModelBinding.ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(ArticleId))
            {
                return(false);
            }

            var    valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            string value = (valueProviderResult != null) ? valueProviderResult.AttemptedValue : null;

            if (value == null)
            {
                throw new WebApi.HttpResponseException(HttpStatusCode.BadRequest);
            }

            bindingContext.Model = new ArticleId(value);
            return(true);
        }
Example #27
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var key = bindingContext.ModelName;
            var val = bindingContext.ValueProvider.GetValue(key);

            if (val != null)
            {
                var s = val.AttemptedValue;
                if (s != null)
                {
                    try
                    {
                        var elementType = bindingContext.ModelType.GetElementType();
                        var converter   = TypeDescriptor.GetConverter(elementType);
                        var values      = Array.ConvertAll(s.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries),
                                                           x => { return(converter.ConvertFromString(x != null ? x.Trim() : x)); });

                        var typedValues = Array.CreateInstance(elementType, values.Length);

                        values.CopyTo(typedValues, 0);

                        bindingContext.Model = typedValues;
                    }
                    catch
                    {
                        bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);
                    }
                }
                else
                {
                    // change this line to null if you prefer nulls to empty arrays
                    bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);
                }
                return(true);
            }
            return(false);
        }
Example #28
0
        public TModelSave BindModelFromMultipartRequest <TModelSave>(HttpActionContext actionContext, ModelBindingContext bindingContext)
            where TModelSave : IHaveUploadedFiles
        {
            var result = actionContext.ReadAsMultipart(SystemDirectories.TempFileUploads);

            var model = actionContext.GetModelFromMultipartRequest <TModelSave>(result, "contentItem");

            //get the files
            foreach (var file in result.FileData)
            {
                //The name that has been assigned in JS has 2 or more parts. The second part indicates the property id
                // for which the file belongs, the remaining parts are just metadata that can be used by the property editor.
                var parts = file.Headers.ContentDisposition.Name.Trim('\"').Split('_');
                if (parts.Length < 2)
                {
                    var response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest);
                    response.ReasonPhrase = "The request was not formatted correctly the file name's must be underscore delimited";
                    throw new HttpResponseException(response);
                }
                var propAlias = parts[1];

                //if there are 3 parts part 3 is always culture
                string culture = null;
                if (parts.Length > 2)
                {
                    culture = parts[2];
                    //normalize to null if empty
                    if (culture.IsNullOrWhiteSpace())
                    {
                        culture = null;
                    }
                }

                //if there are 4 parts part 4 is always segment
                string segment = null;
                if (parts.Length > 3)
                {
                    segment = parts[3];
                    //normalize to null if empty
                    if (segment.IsNullOrWhiteSpace())
                    {
                        segment = null;
                    }
                }

                // TODO: anything after 4 parts we can put in metadata

                var fileName = file.Headers.ContentDisposition.FileName.Trim('\"');

                model.UploadedFiles.Add(new ContentPropertyFile
                {
                    TempFilePath  = file.LocalFileName,
                    PropertyAlias = propAlias,
                    Culture       = culture,
                    Segment       = segment,
                    FileName      = fileName
                });
            }

            bindingContext.Model = model;

            return(model);
        }
Example #29
0
 public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
 {
     return(true);
 }
 /// <summary>
 /// Binds the model.
 /// </summary>
 /// <param name="controllerContext">The controller context.</param>
 /// <param name="bindingContext">The binding context.</param>
 /// <returns></returns>
 public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
 {
     try
     {
         HttpRequestBase request = new HttpRequestWrapper(HttpContext.Current.Request);
         if (request.Form.AllKeys.Length > 0)
         {
             bindingContext.Model = GetDataFromFormContext <UserImageRequestDto>(request.Form[0]);
         }
         return(true);
     }
     catch (Exception ex)
     {
         ex.ExceptionValueTracker(actionContext, bindingContext);
     }
     return(false);
 }