自动匹配HTTP请求中对应实体参数名的数据

自动匹配HTTP请求中对应实体参数名的数据

        /// <summary>
/// 获取请求参数字段
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetRequestParas<T>()
{ 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;
} /// <summary>
/// 转换方法
/// </summary>
/// <param name="convertibleValue">待转换内容</param>
/// <param name="t">新的类型</param>
/// <returns>转换后的内容,如果转换不成功,返回null</returns>
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;
} /// <summary>
/// 执行TryParse方法进行转换
/// </summary>
/// <param name="value">待转换内容</param>
/// <param name="type">新的类型</param>
/// <returns>转换后的内容,如果转换不成功,返回null</returns>
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;
} /// <summary>
/// 执行反射的方法
/// </summary>
/// <param name="methodName">方法名</param>
/// <param name="types">参数类型</param>
/// <param name="invokeArgs">参数值</param>
/// <param name="invokeArgs">方法所在类的类型</param>
/// <returns></returns>
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请求中对应实体参数名的数据,就是这样,其它的方法也可以单独用的,不过单独用的话最好写成扩展方法,直接点出来。

04-25 21:15