看到.net webapi中有[FromUri]来接收参数 可以将自动参数转换成字段属性的类型
baidu 了许多文章 都在自己造轮子 突然发下微软提供了这个方法 Convert.ChangeType()
public static readonly BackArgs _args = new BackArgs(); protected override void OnInit(EventArgs e) { foreach (System.Reflection.PropertyInfo item in typeof(BackArgs).GetProperties()) { if (Request.Params[item.Name] != null) { item.SetValue(_args, Convert.ChangeType(Request.Params[item.Name], Type.GetType(item.PropertyType.FullName))); } } }
新版本
public static class ObjectMapper { public static TDestination Map<TDestination>(this TDestination objects, object source) where TDestination : class, new() { switch (source) { case HttpRequest request: objects = JsonConvert.DeserializeObject<TDestination>(JsonConvert.SerializeObject(request.Params.AllKeys.ToDictionary(x => x, x => request.Params[x]))); break; case IDictionary<string, string> keyValuePairs: objects = JsonConvert.DeserializeObject<TDestination>(JsonConvert.SerializeObject(keyValuePairs)); break; default: break; } return objects; } }