C#端读写Cookie
一在C# 代码中简单的读写Cookie
1) 写Cookie
HttpCookie cookie = new HttpCookie("CookieName",”cookieValue”);
Response.Cookies.add(cookie);
2)读取Cookie
HttpCookie cookie = Request.Cookies["CookieName "];
String value=cookie.Value;
二 把一个类做为cookie进行读写
先定义一个DisplaySettings类:
public class DisplaySettings
{
public int Style;
public int Size;
public override stringToString()
{
returnstring.Format("Style={0},Size={1}",this.Style,this.Size);
}
}
有两种方式对此类进行读写Cookie
1) 第一种方式读写
//以第一种方式写cookie
public static voidWriteCookie_1()
{
DisplaySettingssettings = new DisplaySettings{ Style=1,Size=33};
HttpCookiecookie = new HttpCookie("DisplaySettings1");
cookie["Style"]= settings.Style.ToString();
cookie["Size"]= settings.Size.ToString();
HttpContext.Current.Response.Cookies.Add(cookie);//写入cookie
}
//以第一种方式读cookie
public static DisplaySettingsReaderCookie_1()
{
HttpCookiecookie = HttpContext.Current.Request.Cookies["DisplaySettings1"];
DisplaySettingssettings = new DisplaySettings();
settings.Style =Convert.ToInt32(cookie["Style"]);
settings.Size = Convert.ToInt32(cookie["Size"]);
returnsettings;
}
2) 第二种方式读写
//the second method to write cookie
public static voidWriteCookie_2()
{
DisplaySettingssetting = new DisplaySettings{ Style = 2, Size = 55 };
HttpCookiecookie = new HttpCookie("DisplaySettings2",Helper.ToJson(setting));
HttpContext.Current.Response.Cookies.Add(cookie);
}
///<summary>
/// the second method to read cookie
///</summary>
///<returns></returns>
public static DisplaySettingsReaderCookie_2()
{
HttpCookiecookie = HttpContext.Current.Request.Cookies["DisplaySettings2"];
if(cookie == null)
return new DisplaySettings();
DisplaySettingssetting = Helper.FromJson<DisplaySettings>(cookie.Value);
returnsetting;
}
用第二种方式,需要添加两个辅助方法,代码如下;
public static class Helper
{
///<summary>
/// a object transformation json string
///</summary>
///<paramname="obj"></param>
///<returns></returns>
public static string ToJson(this object obj)
{
if(obj == null)
returnstring.Empty;
JavaScriptSerializerjss = new JavaScriptSerializer();
returnjss.Serialize(obj);
}
///<summary>
/// json transformation a object
///</summary>
///<typeparamname="T"></typeparam>
///<paramname="cookie"></param>
///<returns></returns>
public static T FromJson<T>(thisstring cookie)
{
if(string.IsNullOrEmpty(cookie))
returndefault(T);
JavaScriptSerializerjss = new JavaScriptSerializer();
returnjss.Deserialize<T>(cookie);
}
}
在js端读写Cookie
在js端读写cookie会用到document.cookie,例如:
<input type="button" value="js写cookie" id="btnWrite" />
<input type="button" value="js读cookie" id="btnRead" />
<script type="text/javascript">
$("#btnWrite").click(function () {
varcookie = "cookie_js=22222;path=/";
document.cookie = cookie;
});
$("#btnRead").click(function () {
varcookie = document.cookie;
alert(cookie);
});
</script>
此方式得到的document.cookie会的到所有Cookie的值,如果只想得到设定的cookie值,可以用jQuery插件实现,此插件具体的代码为:
/**
*Create a cookie with the given name and value and other optional parameters.
*
*@example $.cookie('the_cookie', 'the_value');
*@desc Set the value of a cookie.
*@example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain:'jquery.com', secure: true});
*@desc Create a cookie with all available options.
*@example $.cookie('the_cookie', 'the_value');
*@desc Create a session cookie.
*@example $.cookie('the_cookie', null);
*@desc Delete a cookie by passing null as value.
*
*@param String name The name of the cookie.
*@param String value The value of the cookie.
*@param Object options An object literal containing key/value pairs to provideoptional cookie attributes.
*@option Number|Date expires Either an integer specifying the expiration datefrom now on in days or a Date object.
* If a negativevalue is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null oromitted, the cookie will be a session cookie and will not be retained
* when the thebrowser exits.
*@option String path The value of the path atribute of the cookie (default: pathof page that created the cookie).
*@option String domain The value of the domain attribute of the cookie (default:domain of page that created the cookie).
*@option Boolean secure If true, the secure attribute of the cookie will be setand the cookie transmission will
* require a secureprotocol (like HTTPS).
*@type undefined
*
*@name $.cookie
*@cat Plugins/Cookie
*@author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
*Get the value of a cookie with the given name.
*
*@example $.cookie('the_cookie');
*@desc Get the value of a cookie.
*
*@param String name The name of the cookie.
*@return The value of the cookie.
*@type String
*
*@name $.cookie
*@cat Plugins/Cookie
* @authorKlaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (name, value, options) {
if (typeof value != 'undefined'){ // name and value given, set cookie
options = options || {};
if(value === null) {
value = '';
options.expires = -1;
}
varexpires = '';
if(options.expires && (typeofoptions.expires == 'number' ||options.expires.toUTCString)) {
vardate;
if(typeof options.expires == 'number') {
date = newDate();
date.setTime(date.getTime() +(options.expires * 24 * 60 * 60 * 1000));
} else{
date = options.expires;
}
expires = ';expires=' + date.toUTCString(); // useexpires attribute, max-age is not supported by IE
}
varpath = options.path ? '; path=' +options.path : '';
vardomain = options.domain ? '; domain=' +options.domain : '';
varsecure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path,domain, secure].join('');
} else { // only name given, get cookie
varcookieValue = null;
if(document.cookie && document.cookie != ''){
varcookies = document.cookie.split(';');
for(var i = 0; i < cookies.length; i++) {
varcookie = jQuery.trim(cookies[i]);
//Does this cookie string begin with the name we want?
if(cookie.substring(0, name.length + 1) == (name + '=')){
cookieValue =decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
returncookieValue;
}
};
文章转载于:http://www.cnblogs.com/fish-li/archive/2011/07/03/2096903.html