有选择的复制对象,即根据客户端传值来复制对象属性值
有选择的复制对象,即根据客户端传值来复制对象属性值
第一个方法是接收调用方发来的参数列表,此方法很有用。
第二个方法是根据调用方发来的参数来更新target对象,而不是只要source对象都更新为target对象的值。
其中,第二个对象复制方法中,有对象属性有别名的情况,不需要的话可以直接删掉相关代码。
private Dictionary<string, object> GetPostData()
{
Dictionary<string, object> dic = new Dictionary<string, object>();
var context = Request.Properties["MS_HttpContext"] as System.Web.HttpContextBase;
var request = context.Request;
foreach (string key in request.QueryString.Keys) dic[key] = request.QueryString[key];
foreach (string key in request.Form.Keys) dic[key] = request.Form[key];
var stream = context.Request.InputStream;
stream.Seek(0, System.IO.SeekOrigin.Begin);
stream.Position = 0;
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
IDictionary<string, JToken> data = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
data.ForEach(p => dic[p.Key] = p.Value);
}
return dic;
}
{
Dictionary<string, object> dic = new Dictionary<string, object>();
var context = Request.Properties["MS_HttpContext"] as System.Web.HttpContextBase;
var request = context.Request;
foreach (string key in request.QueryString.Keys) dic[key] = request.QueryString[key];
foreach (string key in request.Form.Keys) dic[key] = request.Form[key];
var stream = context.Request.InputStream;
stream.Seek(0, System.IO.SeekOrigin.Begin);
stream.Position = 0;
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
IDictionary<string, JToken> data = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
data.ForEach(p => dic[p.Key] = p.Value);
}
return dic;
}
/// 对象属性复制,该方法依赖HttpContent请求
/// </summary>
/// <param name="target"></param>
/// <param name="source"></param>
private void TryUpdateModel(IMember target, IMember source)
{
object value = null;
if (target == null)
{
target = new ThreeMMember();
}
var PropertyList = source.GetType().GetProperties();
var props = PropertyList.Select(p => p.Name).Join(GetPostData().Keys.ToArray(), p => p, p => p, (a, b) => a).Except(new List<string> { "Code" });
foreach (var prop in props)
{
var pp = PropertyList.FirstOrDefault(p => p.Name == prop);
value = pp.GetValue(source);
var att = pp.GetCustomAttributes(typeof(BsonElementAttribute), true) as BsonElementAttribute[];
var pp1 = att.Any() ? att.FirstOrDefault().ElementName : prop;
target.SetProperty(pp1, value);
}
}