1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Text.RegularExpressions; 5 6 namespace DotNet.Utilities 7 { 8 ... ...
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Text.RegularExpressions; 5 6 namespace DotNet.Utilities 7 { 8 /// <summary> 9 /// Cookie操作幫助類 10 /// </summary> 11 public static class HttpCookieHelper 12 { 13 /// <summary> 14 /// 根據字元生成Cookie列表 15 /// </summary> 16 /// <param name="cookie">Cookie字元串</param> 17 /// <returns></returns> 18 public static List<CookieItem> GetCookieList(string cookie) 19 { 20 List<CookieItem> cookielist = new List<CookieItem>(); 21 foreach (string item in cookie.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries)) 22 { 23 if (Regex.IsMatch(item, @"([\s\S]*?)=([\s\S]*?)$")) 24 { 25 Match m = Regex.Match(item, @"([\s\S]*?)=([\s\S]*?)$"); 26 cookielist.Add(new CookieItem() { Key = m.Groups[1].Value, Value = m.Groups[2].Value }); 27 } 28 } 29 return cookielist; 30 } 31 32 /// <summary> 33 /// 根據Key值得到Cookie值,Key不區分大小寫 34 /// </summary> 35 /// <param name="Key">key</param> 36 /// <param name="cookie">字元串Cookie</param> 37 /// <returns></returns> 38 public static string GetCookieValue(string Key, string cookie) 39 { 40 foreach (CookieItem item in GetCookieList(cookie)) 41 { 42 if (item.Key == Key) 43 return item.Value; 44 } 45 return ""; 46 } 47 /// <summary> 48 /// 格式化Cookie為標準格式 49 /// </summary> 50 /// <param name="key">Key值</param> 51 /// <param name="value">Value值</param> 52 /// <returns></returns> 53 public static string CookieFormat(string key, string value) 54 { 55 return string.Format("{0}={1};", key, value); 56 } 57 } 58 59 /// <summary> 60 /// Cookie對象 61 /// </summary> 62 public class CookieItem 63 { 64 /// <summary> 65 /// 鍵 66 /// </summary> 67 public string Key { get; set; } 68 /// <summary> 69 /// 值 70 /// </summary> 71 public string Value { get; set; } 72 } 73 }