網絡請求的參數過濾,排序,拼接,加密.也參考了alipay.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ICE.Common { public class WebCore { /// <summary> /// 除去數組中的空值和簽名參數並以字母a到z的順序排序 /// </summary> /// <param name="dicArrayPre">過濾前的參數組</param> /// <returns>過濾後的參數組</returns> public static Dictionary<string, string> FilterPara(SortedDictionary<string, string> dicArrayPre) { Dictionary<string, string> dicArray = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> temp in dicArrayPre) { if (temp.Key.ToLower() != "sign" && temp.Key.ToLower() != "sign_type" && temp.Value != "" && temp.Value != null) { dicArray.Add(temp.Key, temp.Value); } } return dicArray; } /// <summary> /// 把數組所有元素,按照“參數=參數值”的模式用“&”字符拼接成字符串 /// </summary> /// <param name="sArray">需要拼接的數組</param> /// <returns>拼接完成以後的字符串</returns> public static string CreateLinkString(Dictionary<string, string> dicArray) { StringBuilder prestr = new StringBuilder(); foreach (KeyValuePair<string, string> temp in dicArray) { prestr.Append(temp.Key + "=" + temp.Value + "&"); } //去掉最後一個&字符 int nLen = prestr.Length; prestr.Remove(nLen - 1, 1); return prestr.ToString(); } private static string BuildRequestMysign(Dictionary<string, string> sPara) { //把數組所有元素,按照“參數=參數值”的模式用“&”字符拼接成字符串 string prestr = CreateLinkString(sPara); //把最終的字符串簽名,獲得簽名結果 string mysign = ""; mysign = IceEncrypt.GetMD5(prestr); return mysign; } } }