標籤:
前言
在http請求的時候,特別是我們使用post請求的時候,都要將請求的參數轉化為url參數,如:a=xxxx&b=xxxx,我們一般都是習慣於使用實體來傳送參數,比如OrderRequest 類,這就產生了從實體轉化為url參數的過程。 實體轉化為url帶參的方法
public static class UrlHelper { public static string ObjectToQuery<T>(this T obj, bool isAddEmptyValue = true, string orderBy = null, string removeFiled = null /*移除那個欄位*/, string fieldReplace = null /*格式old,name*/) where T : class { if (obj == null) { return ""; } var properties = obj.GetType().GetProperties(); var list = new List<string>(); foreach (var item in properties) { if (removeFiled != null && item.Name == removeFiled) { //移除不必要欄位 continue; } var proValue = item.GetValue(obj, null); if ((proValue != null && !string.IsNullOrEmpty(proValue.ToString())) || isAddEmptyValue) { var value = proValue != null ? proValue.ToString() : ""; value = value.Replace("+", "%20"); var filedName = item.Name; //替換key名字,如xxx_Name替換為xxx[0].Name if (!string.IsNullOrEmpty(fieldReplace)) { var arry = fieldReplace.Split(‘$‘); if (arry.Length > 1) { filedName = filedName.Replace(arry[0], arry[1]); } } list.Add(filedName + "=" + value); } } if (orderBy != null) { switch (orderBy) { case "asc": { list = list.OrderBy(m => m).ToList(); break; } default: { list = list.OrderByDescending(m => m).ToList(); break; } } } return string.Join("&", list); } }具體參數的意思: 1、 isAddEmptyValue:是否去掉如果值為空白的實體,如:a=&b=xxxx&c=xxxxx,就會將a去除2、orderBy :是按字母的升序還是降序進行排序3、removeFiled:移除哪些欄位以及值,主要是有些實體雖然有賦值,但是不需要傳4、fieldReplace:主要是替換關鍵字的,比如我們url要求是passagner[0].name,由於C#不支援[0].這樣命名變數名,因此可以將其先命名為passagener__name,然後是__$[0]這樣替換 執行個體
class Program { static void Main(string[] args) { TestRequest testRequest = new TestRequest() { contactMobile = "133xxxxxxx", contactUser = "測試", passengers__idNumber = "440103xxxxxxxx", passengers__idType = "1", passengers__name = "測試" }; Console.WriteLine("{0}", UrlHelper.ObjectToQuery(testRequest,fieldReplace:"__$[0].",removeFiled:"contactUser")); Console.ReadLine(); } }
結果為:
結論: 1、實體轉化為url經常會使用, 2、.net不支援變數名為passagener[0].name 這樣的命名, 3、以後還可以根據自己的情況進行擴充
.net將實體轉成url參數