两端读写Cookies(服务器端C#、客户端Javascript)

 C# 读写Cookies

public string CookieValue
{
get{ return this.txtCookies.text;}
set{ this.txtCookies.text=value.ToString();}
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
       CookieValue=GetCookies();
    
    if (GetCookies() != CookieValue)
       SetCookies(CookieValue);
}
private void SetCookies(string cookieValue)
{
    string key = {CookieName}+ ("_" + {用户ID或是其它整型}).GetHashCode().ToString();  //GetHashCode(),做伪装处理
    HttpCookie cookie = new HttpCookie(key, cookieValue)
    cookie.Expires = DateTime.Now.AddYears(1);
    cookie.Domain = ".blog.51cto.com";
    Response.Cookies.Add(cookie);
}
private string GetCookies()
{
    string key = {CookieName}+ ("_" + {用户ID或是其它整型}).GetHashCode().ToString();
    if (Request.Cookies[key] != null)
    {
       return Request.Cookies[key].Value == null ? "1" : Request.Cookies[key].Value.ToString();
    }
    return "{默认值}";
}
 
 
Javascript 读写Cookies
 
function FunctionName(cookieValue) {
    if (getcookie(colorKey) != cookieValue ) {
        addcookie(colorKey, cookieValue , (365 * 24));
    }
}
function addcookie(name, value, expireHours) {
    var cookieString = name + "=" + escape(value);
    //判断是否设置过期时间
    if (expireHours > 0) {
        var date = new Date();
        date.setTime(date.getTime + expireHours * 3600 * 1000);
        cookieString = cookieString + "; expire=" + date.toGMTString();
    }
    document.cookie = cookieString;
}
 
function getcookie(name) {
    var strcookie = document.cookie;
    var arrcookie = strcookie.split("; ");
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) return arr[1];
    }
    return "{默认值}";
}
 

你可能感兴趣的:(JavaScript,C#,Cookies,读取,写入)