silverlight操作cookie
时间:2011-03-15 来源:YLWS
using System.Windows.Browser;
namespace SilverlightApplication1
{
public class CookieHelp
{
//添加cookie
public void SetCookie(string key, string value)
{
DateTime expires = DateTime.Now + TimeSpan.FromDays(7); //cookie的有效时间
string cookie = String.Format("{0}={1};expires={2}", key, value, expires.ToString("R"));
HtmlPage.Document.SetProperty("cookie", cookie);
}
//删除cookie,使用一个过期的cookie替代
public void DelCookie(string key)
{
DateTime expires = DateTime.Now - TimeSpan.FromDays(1); //将有效时间换成昨天
string cookie = String.Format("{0}=;expires={1}", key, expires.ToString("R"));
HtmlPage.Document.SetProperty("cookie", cookie);
}
//获取cooike对应键值
public string GetCookie(string key)
{
string[] cookies = HtmlPage.Document.Cookies.Split(';');//cookie里含多对值,将值按;分割
foreach (string cookie in cookies)
{
string[] value = cookie.Split('=');//获取=两边的值
if (value.Length == 2)
{
if (value[0].ToString() == key)//判断键名
{
return value[1];//返回键值
}
}
}
return "";
}
//获取cookie键值linq表达式
public 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;
}
}
}
相关阅读 更多 +