看到.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; } }