在Silverlight应用程序中操作Cookie
删除Cookie
删除Cookie非常简单,清空Cookie的值并设置它的过期时间,如下代码所示:
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); }
Cookie帮助类
由于在开发中,我们可能会经常用到对于Cookie的操作,我在这里总结了一个简单的Silverlight中操作Cookie帮助类,大家可以直接在自己的项目中使用,主要有如下几个功能:
1.写入Cookie
2.读取Cookie
3.删除Cookie
4.判断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)); } }
总结
本文介绍了在Silverlight应用程序中如何操作Cookie,希望对大家有所帮助。