技巧:在Silverlight应用程序中操作Cookie
void btnSet_Click(object sender, RoutedEventArgs e) { DateTime expir = DateTime.UtcNow + TimeSpan.FromDays(7); String cookie = String.Format("{0}={1};expires={2}", this.txtKey.Text, this.txtValue.Text, expir.ToString("R")); HtmlPage.Document.SetProperty("cookie", cookie); }
public sealed class HtmlDocument : HtmlObject { public string Cookies { get{ HtmlPage.VerifyThread(); String property = this.GetProperty("cookie") as String; if (property != null) { return property; } return String.Empty; } set{ HtmlPage.VerifyThread(); String str = value; if (String.IsNullOrEmpty(str)) { str = string.Empty; } this.SetProperty("cookie", str); } } }
void btnRetrieve_Click(object sender, RoutedEventArgs e) { String[] cookies = HtmlPage.Document.Cookies.Split(';'); foreach (String cookie in cookies) { String[] keyValues = cookie.Split('='); if (keyValues.Length == 2) { if (keyValues[0].Trim() == this.txtKey.Text.Trim()) { this.txtValue.Text = keyValues[1]; } } } }
void btnDelete_Click(object sender, RoutedEventArgs e) { DateTime expir = DateTime.UtcNow - TimeSpan.FromDays(1); string cookie = String.Format("{0}=;expires={1}", this.txtKey.Text, expir.ToString("R")); HtmlPage.Document.SetProperty("cookie", cookie); }
public class CookiesUtils { public static void SetCookie(String key, String value) { SetCookie(key, value, null, null, null, false); } public static void SetCookie(String key, String value, TimeSpan expires) { SetCookie(key, value, expires, null, null, false); } public static void SetCookie(String key, String value, TimeSpan? expires, String path, String domain, bool secure) { StringBuilder cookie = new StringBuilder(); cookie.Append(String.Concat(key, "=", value)); if (expires.HasValue) { DateTime expire = DateTime.UtcNow + expires.Value; cookie.Append(String.Concat(";expires=", expire.ToString("R"))); } if (!String.IsNullOrEmpty(path)) { cookie.Append(String.Concat(";path=", path)); } if (!String.IsNullOrEmpty(domain)) { cookie.Append(String.Concat(";domain=", domain)); } if (secure) { cookie.Append(";secure"); } HtmlPage.Document.SetProperty("cookie", cookie.ToString()); } public static string GetCookie(String key) { String[] cookies = HtmlPage.Document.Cookies.Split(';'); String result = (from c in cookies let keyValues = c.Split('=') where keyValues.Length == 2 && keyValues[0].Trim() == key.Trim() select keyValues[1]).FirstOrDefault(); return result; } public static void DeleteCookie(String key) { DateTime expir = DateTime.UtcNow - TimeSpan.FromDays(1); string cookie = String.Format("{0}=;expires={1}", key, expir.ToString("R")); HtmlPage.Document.SetProperty("cookie", cookie); } public static bool Exists(String key, String value) { return HtmlPage.Document.Cookies.Contains(String.Format("{0}={1}", key, value)); } }
本文出自 “TerryLee技术专栏” 博客,请务必保留此出处http://terrylee.blog.51cto.com/342737/89836