夸克之书

  • 首页
  • 科普
  • 笔记
  • .NET/C#
  • 物联网
  • 算法
  • Linux
  • 树莓派
夸克之内,别有洞天
  1. 首页
  2. .NET/C#
  3. 正文

C# HTTP请求参数转实体类

2018-12-20 5570点热度 0人点赞 0条评论

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

将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

本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2020-12-13

afirefish

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

您需要 登录 之后才可以评论
放松一下
https://www.quarkbook.com/wp-content/uploads/2021/05/凤凰传奇-海底(Live).flac
分类
  • .NET/C#
  • Linux
  • 树莓派
  • 物联网
  • 科普
  • 笔记
  • 算法
  • 默认
最新 热点 随机
最新 热点 随机
在代码中判断龙芯新旧世界平台 Windows获取固定后缀的IPv6地址 目前为止,你可能找不到第二台支持志强的1L小主机(P350 Tiny+W-1350+ECC+双NVME+PCIE扩展)!!! iKuai(爱快)实现成都移动IPTV IPoE拨号 Linux EXT4分区误删除后数据恢复 C#连接到巴法云
在代码中判断龙芯新旧世界平台
树莓派4B配置U盘启动 维持宇宙的四种“力量”——关于四大基本力 将Emby作为Windows服务运行,并访问NAS上的媒体库 Winform设置程序开机启动 Windows获取固定后缀的IPv6地址 IIS应用程序池两种运行模式:集成模式和经典模式。
最近评论
Eagle 发布于 8 个月前(10月21日) 参考博主教程成功搞定了成都移动IPTV组播转单播,电脑、手机都可以播放了。但目前有个问题,原IPTV...
rundoze 发布于 10 个月前(08月31日) 牛逼
cc21216695 发布于 2 年前(09月27日) 试了一下,加入启动项也无效,压根没有用
afirefish 发布于 3 年前(11月28日) 非常感谢,非常棒!
》随缘《 发布于 3 年前(11月20日) 最新【一键处理】方法: https://github.com/MrXhh/VSTools/rele...
书签
  • 打赏
  • 毒鸡汤
  • 米店
  • 金鱼直播间

COPYRIGHT © 2023 quarkbook.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备15036129号-9

登录
注册|忘记密码?