using ServiceStack.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web; namespace restService.Interface.Helper
{
public static class EntityHelper
{
/// <summary>
/// 将HTTP上下文表单内容转为实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <returns></returns>
public static T RequestToModel<T>(this HttpContext context) where T : new()
{
T model = new T();
Type type = model.GetType();
PropertyInfo[] Fields = type.GetProperties();
for (int i = ; i < Fields.Count(); i++)
{
var name = Fields[i].Name;
Type vtype = Fields[i].PropertyType;
var value = context.Request[name];
if (value != null)
{
if (vtype.Name.ToLower().IndexOf("int") >= )//int
{
var v = Convert.ToInt32(value);
Fields[i].SetValue(model, v);
continue;
}
if (vtype.Name.ToLower().IndexOf("string") >= )//string
{
var v = Convert.ToString(value);
Fields[i].SetValue(model, v);
continue;
}
if (vtype.Name.ToLower().IndexOf("datetime") >= )//datetime
{
var v = Convert.ToDateTime(value);
Fields[i].SetValue(model, v);
}
if (vtype.Name.ToLower().IndexOf("bool") >= )//datetime
{
var v = Convert.ToBoolean(value);
Fields[i].SetValue(model, v);
}
}
}
return model;
}
/// <summary>
/// 将HTTP上下文表单内容转为实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <returns></returns>
public static T RequestToModel<T>(this IRequest context) where T : new()
{
T model = new T();
Type type = model.GetType();
PropertyInfo[] Fields = type.GetProperties();
for (int i = ; i < Fields.Count(); i++)
{
var name = Fields[i].Name;
Type vtype = Fields[i].PropertyType;
string value = context.QueryString[name];
if(value==null)
value = context.FormData[name];
if (value != null)
{
if (vtype.Name.ToLower().IndexOf("int") >= )//int Nullable
{
var v = Convert.ToInt32(value);
Fields[i].SetValue(model, v);
continue;
}
if (vtype.Name.ToLower().IndexOf("nullable") >= )//Nullable
{
var v = Convert.ToDecimal(value);
Fields[i].SetValue(model, v);
continue;
}
if (vtype.Name.ToLower().IndexOf("string") >= )//string
{
var v = Convert.ToString(value);
Fields[i].SetValue(model, v);
continue;
}
if (vtype.Name.ToLower().IndexOf("datetime") >= )//datetime
{
var v = Convert.ToDateTime(value);
Fields[i].SetValue(model, v);
}
if (vtype.Name.ToLower().IndexOf("bool") >= )//datetime
{
var v = Convert.ToBoolean(value);
Fields[i].SetValue(model, v);
}
}
}
return model;
}
/// <summary>
/// 获取数据
/// </summary>
/// <param name="context"></param>
/// <param name="key">关键字</param>
/// <returns></returns>
public static String GetDataParameter(this IRequest context,string key)
{
string result = context.FormData[key];
if (result == null)
result = context.QueryString[key];
return result;
}
}
}