自动匹配HTTP请求中对应实体参数名的数据(性能不是最优)
发布日期:2021-08-13 19:50:48 浏览次数:13 分类:技术文章

本文共 3484 字,大约阅读时间需要 11 分钟。

///         /// 获取请求参数字段        ///         /// 
///
public static T GetRequestParas
() { T t = (T)Activator.CreateInstance(typeof(T)); if (HttpContext.Current == null) { return t; } if (HttpContext.Current.Request.Form.Count < 0 && HttpContext.Current.Request.QueryString.Count < 0) { return t; } //获取所有为Public的字段和实例成员(如果有的话) PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); //遍历每一个字段 foreach (PropertyInfo p in props) { var value = HttpContext.Current.Request[p.Name.ToLower()]; if (value != null) { var okvalue = ConvertTo(value, p.PropertyType); if (okvalue == null) { okvalue = ConverUtil.toObject(value); } p.SetValue(t, okvalue, null); } } return t; } ///
/// 转换方法 /// ///
待转换内容 ///
新的类型 ///
转换后的内容,如果转换不成功,返回null
public static object ConvertTo( IConvertible convertibleValue,Type t) { if (null == convertibleValue) { return null; } if (!t.IsGenericType) { return Convert.ChangeType(convertibleValue, t); } else { Type genericTypeDefinition = t.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return ConverValue(convertibleValue.toString(), Nullable.GetUnderlyingType(t)); // Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(t)); } } return null; } ///
/// 执行TryParse方法进行转换 /// ///
待转换内容 ///
新的类型 ///
转换后的内容,如果转换不成功,返回null
public static object ConverValue(string value, Type type) { Object testValue = Activator.CreateInstance(type); object[] invokeArgs = new object[] { value, testValue }; Type[] types = new Type[2]; types[0] = typeof(string); types[1] = type.MakeByRefType(); var isok = RunMethod("TryParse", types, invokeArgs, type); bool outok = false; bool.TryParse(isok.toString(), out outok); if (outok) { return invokeArgs[1]; } return null; } ///
/// 执行反射的方法 /// ///
方法名 ///
参数类型 ///
参数值 ///
方法所在类的类型 ///
public static object RunMethod(string methodName, Type[] types, object[] invokeArgs, Type type) { Object Value = Activator.CreateInstance(type); MethodInfo mi = type.GetMethod(methodName, types); if (mi == null) { return null; } Object returnValue = mi.Invoke(Value, invokeArgs); return returnValue; }

  写了大半天才写好,累死了。

方法的作用是自动匹配HTTP请求中对应实体参数名的数据,就是这样,其它的方法也可以单独用的,不过单独用的话最好写成扩展方法,直接点出来。

转载于:https://www.cnblogs.com/qiywtc/p/5482789.html

转载地址:https://blog.csdn.net/weixin_30699235/article/details/99157063 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:支付宝勒索病毒
下一篇:PHP实现.csv文件的上传与下载-Mysql

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月25日 18时23分51秒