技巧:在Silverlight應用程式中操作Cookie

來源:互聯網
上載者:User
概述

很多朋友來信問如何在Silverlight 2中操作Cookie,這裡專門寫篇文章介紹一下。為了實現在Silverlight應用程式中對於Cookie的操作,我們需要藉助於HtmlPage.Document對象。

在使用HtmlPage.Document之前,請先添加System.Windows.Browser命名空間。本文介紹了如何在Silverlight應用程式中操作Cookie,並在最後給出了一個操作Cookie的公用類,大家可以直接在自己的應用程式中使用。

寫入Cookie

在Silverlight 應用程式中,我們可以通過HtmlPage.Document.SetProperty方法來設定Cookie或者使用HtmlPage.Document對象的Cookies屬性(後面會講到),如下代碼所示:

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);}

這裡設定Cookie的到期時間為一周,除了設定到期時間外還可以設定domain、path等,後面的協助類中你將看到這一點。

如使用下面的介面寫入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];            }        }    }}

如所示:

刪除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,希望對大家有所協助。

本文範例程式碼以及CookiesUtils代碼下載:

更多Silverlight 2的文章請參考Silverlight 2 相關文章匯總。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.