標籤:trim dex color tin count sub 類型 重複項 bst
httpcode版本
/// <summary> /// 合并Cookie,將cookie2與cookie1合并更新 返回字串類型Cookie /// </summary> /// <param name="cookie1">舊cookie</param> /// <param name="cookie2">新cookie</param> /// <returns></returns> public string UpdateCookie(string cookie1, string cookie2) { StringBuilder sb = new StringBuilder(); Dictionary<string, string> dicCookie = new Dictionary<string, string>(); //遍曆cookie1 if (!string.IsNullOrEmpty(cookie1)) { foreach (string cookie in cookie1.Replace(‘,‘, ‘;‘).Split(‘;‘)) { if (!string.IsNullOrEmpty(cookie) && cookie.IndexOf(‘=‘) > 0) { string key = cookie.Split(‘=‘)[0].Trim(); string value = cookie.Substring(key.Length + 1).Trim(); if (dicCookie.ContainsKey(key)) { dicCookie[key] = cookie; } else { dicCookie.Add(key, cookie); } } } } if (!string.IsNullOrEmpty(cookie2)) { //遍曆cookie2 foreach (string cookie in cookie2.Replace(‘,‘, ‘;‘).Split(‘;‘)) { if (!string.IsNullOrEmpty(cookie) && cookie.IndexOf(‘=‘) > 0) { string key = cookie.Split(‘=‘)[0].Trim(); string value = cookie.Substring(key.Length + 1).Trim(); if (dicCookie.ContainsKey(key)) { dicCookie[key] = cookie; } else { dicCookie.Add(key, cookie); } } } } int i = 0; foreach (var item in dicCookie) { i++; if (i < dicCookie.Count) { sb.Append(item.Value + ";"); } else { sb.Append(item.Value); } } return sb.ToString(); }
萬能架構版本
/// <summary> /// 自動合并兩個Cookie的值返回更新後結果 /// </summary> /// <param name="cookie1">Cookie1</param> /// <param name="cookie2">Cookie2</param> /// <returns>返回更新後的Cookie</returns> internal static string GetMergeCookie(string cookie1, string cookie2) { if (string.IsNullOrWhiteSpace(cookie1))//新的是空的 { return cookie2;//返回老的 } if (string.IsNullOrWhiteSpace(cookie2))//老的是空的 { return cookie1;//返回新的 } List<string> cookielist = new List<string>();//結果 string[] list_1 = cookie1.ToString().Split(‘;‘); string[] list_2 = cookie2.ToString().Split(‘;‘); foreach (string item in list_1) { //排除重複項 if (cookielist.Contains(item)) continue; //對接Cookie基本的Key和Value串 cookielist.Add(string.Format("{0} ", item)); } foreach (string item in list_2) { //排除重複項 if (cookielist.Contains(item)) continue; //對接Cookie基本的Key和Value串 cookielist.Add(string.Format("{0}", item)); } return string.Join(";", cookielist); }
C#cookie合并更新