Пример #1
0
        /// <summary>
        /// Parses the given string value converting it to the given type.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type" /> to convert the string to.</typeparam>
        /// <param name="value">The <see cref="string" /> value to parse.</param>
        /// <param name="culture">The <see cref="CultureInfo" /> to use as the current culture.
        /// <remarks>If not set will parse using <see cref="CultureInfo.InvariantCulture" /></remarks></param>
        /// <returns>
        /// The <typeparamref name="T" />.
        /// </returns>
        public T ParseValue <T>(string value, CultureInfo culture = null)
        {
            if (culture == null)
            {
                culture = CultureInfo.InvariantCulture;
            }

            Type type = typeof(T);

            IQueryParamConverter converter = QueryTypeDescriptor.GetConverter(type);

            if (converter == null && Nullable.GetUnderlyingType(type) is Type underlyingType)
            {
                type      = underlyingType;
                converter = QueryTypeDescriptor.GetConverter(type);
            }

            try
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                return((T)converter.ConvertFrom(culture, HttpUtility.UrlDecode(value), type));
            }
            catch
            {
                // Return the default value
                return(default(T));
            }
        }
Пример #2
0
        /// <summary>
        /// Parses the given string value converting it to the given type.
        /// </summary>
        /// <param name="type">
        /// The <see cref="Type"/> to convert the string to.
        /// </param>
        /// <param name="value">
        /// The <see cref="string"/> value to parse.
        /// </param>
        /// <param name="culture">
        /// The <see cref="CultureInfo"/> to use as the current culture.
        /// <remarks>If not set will parse using <see cref="CultureInfo.InvariantCulture"/></remarks>
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        public object ParseValue(Type type, string value, CultureInfo culture = null)
        {
            if (culture == null)
            {
                culture = CultureInfo.InvariantCulture;
            }

            IQueryParamConverter converter = QueryTypeDescriptor.GetConverter(type);

            try
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                return(converter.ConvertFrom(culture, HttpUtility.UrlDecode(value), type));
            }
            catch
            {
                // Return the default value
                return(TypeDefaultsCache.GetOrAdd(type, t => this.GetDefaultValue(type)));
            }
        }