在Silverlight应用程序中操作Cookie
读取Cookie
我们可以通过HtmlPage.Document.GetProperty方法来获取所有Cookie,另外在HtmlDocument中定义了Cookies属性,已经为我们封装好了GetProperty方法,可以直接使用,它的定义如下代码所示:
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); } } }
如使用下面这段代码来获取一个指定Key的Cookie值:
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]; } } } }
如下图所示: