目前接口统一使用 [FromBody]Dictionary<string,string> req 来接收。

WebApi接口传参

有时候,需要把从req字典提取多个字段赋值给 model,几个还好,几十个赋值就不好了。因此设计了使用泛型、反射帮助赋值。

设计不怎么通用,随着类型的增多,这个需要继续迭代。

public static A MapperThree<A>(Dictionary<string, string> req)
        {
            A a = Activator.CreateInstance<A>();
            try
            {               
                Type Typea = typeof(A);
                foreach (PropertyInfo propertyInfo in Typea.GetProperties())
                {
                    if (req.ContainsKey(propertyInfo.Name))
                    {
                        // Type t = ap.GetType();
                        string proName = propertyInfo.PropertyType.Name;
                        if (proName == "String")
                        {
                            propertyInfo.SetValue(a, req[propertyInfo.Name]);
                        }
                        else if (proName == "Int32")
                        {
                            propertyInfo.SetValue(a, Convert.ToInt32(req[propertyInfo.Name]));
                        }
                        else if (proName == "DateTime")
                        {
                            propertyInfo.SetValue(a, Convert.ToDateTime(req[propertyInfo.Name]));
                        }
                        else if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            
                                Type[] typeArray = propertyInfo.PropertyType.GetGenericArguments();
                                Type baseType = typeArray[0];
                                if (baseType.Name== "Int32")
                                {
                                    propertyInfo.SetValue(a, Convert.ToInt32(req[propertyInfo.Name]));
                                }
                                else if (baseType.Name == "DateTime")
                                {
                                    propertyInfo.SetValue(a, Convert.ToDateTime(req[propertyInfo.Name]));
                                }
                          
                        }
                        else
                        {
                            //非int类型 and string ,datetime类型 不做处理
                        }
                    }                  
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return a;
        }
View Code

相关文章: