using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Store.Framework.Models { public class Cookies : Dictionary { private readonly string oldCookie; public Cookies(string cookie) { oldCookie = cookie; SplitCookie(oldCookie); } /// /// Cookie字符串 /// public string CookieString { get { return GetCookieString(); } } /// /// 拆分Cookie /// private void SplitCookie(string cookie) { this.Clear(); Regex regCookie = new Regex("(?.+?)=(?.+?)(;|$)"); if (regCookie.IsMatch(cookie)) { MatchCollection matchs = regCookie.Matches(cookie); foreach (Match item in matchs) { string key = item.Groups["key"].Value.Trim(); string value = item.Groups["value"].Value.Trim(); if (!ContainsKey(key)) { this.Add(key.Trim(), value.Trim()); } } } } /// /// 获取指定值 /// /// /// 默认值 /// public string GetValue(string key, string defvalue) { if (ContainsKey(key)) { return this[key]; } return defvalue; } /// /// 添加或修改 /// /// /// public void AddOrUpdate(string key, string value) { if (!this.ContainsKey(key)) { Add(key, value); } else { this[key] = value; } } /// /// 获取Cookies字符串 /// /// public virtual string GetCookieString() { var list = this.Select(a => { return $"{a.Key}={a.Value}"; }); return string.Join(";", list); } /// /// 隐式转换 /// /// public static implicit operator string (Cookies cookie) { return cookie.GetCookieString(); } } }