C# HTTP请求参数转实体类

1,004次阅读
没有评论

很多情况下我们都是将实体类转化为请求参数,然而今天我们反着来,将请求的参数转化为实体类。

将HTTP请求参数转化为实体类一般用于HttpServer当中。直接上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Geeiot.Common.Http
{
    public class RequestParamConvertEnity<T>
    {
        /// <summary>
        /// 将实体类通过反射组装成字符串
        /// </summary>
        /// <param name="t">实体类</param>
        /// <returns>组装的字符串</returns>
        public static string GetEntityToString(T t)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            Type type = t.GetType();
            System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties();
            for (int i = 0; i < propertyInfos.Length; i++)
            {
                sb.Append(propertyInfos[i].Name + "=" + propertyInfos[i].GetValue(t, null) + "&");
            }
            return sb.ToString();
        }

        public static T StringConvertEntity<T>(string query)
        {
            try
            {
                string[] array = query.Split('&');
                List<string> queryParam = new List<string>();
                if (array.Length != 0)
                {
                    foreach (var item in array)
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            queryParam.Add(item);
                        }
                    }
                }
                if(queryParam.Count == 0)
                {
                    return default(T);
                }

                string[] temp = null;
                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                foreach (string s in queryParam)
                {
                    temp = s.Split('=');
                    if(temp.Length != 2)
                    {
                        continue;
                    }
                    dictionary.Add(temp[0], temp[1]);
                }
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(T));
                T entry = (T)assembly.CreateInstance(typeof(T).FullName);
                System.Text.StringBuilder sb = new StringBuilder();
                Type type = entry.GetType();
                System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties();
                for (int i = 0; i < propertyInfos.Length; i++)
                {
                    foreach (string key in dictionary.Keys)
                    {
                        if (propertyInfos[i].Name.ToLower() == key.ToString().ToLower())
                        {
                            propertyInfos[i].SetValue(entry, GetObject(propertyInfos[i], dictionary[key]), null);
                            break;
                        }
                    }
                }
                return entry;
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// 转换值的类型
        /// </summary>
        /// <param name="p"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static object GetObject(System.Reflection.PropertyInfo p, string value)
        {
            switch (p.PropertyType.Name.ToString().ToLower())
            {
                case "int16":
                    return Convert.ToInt16(value);
                case "int32":
                    return Convert.ToInt32(value);
                case "int64":
                    return Convert.ToInt64(value);
                case "string":
                    return Convert.ToString(value);
                case "datetime":
                    return Convert.ToDateTime(value);
                case "boolean":
                    return Convert.ToBoolean(value);
                case "char":
                    return Convert.ToChar(value);
                case "double":
                    return Convert.ToDouble(value);
                default:
                    return value;
            }
        }
    }
}

同时,感谢CSDN MYsce提供的参考代码:https://blog.csdn.net/MYsce/article/details/78858861

afirefish
版权声明:本站原创文章,由afirefish2018-12-20发表,共计2348字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
载入中...