这几天在开发项目时遇到一个奇怪的问题,在VS上运行正常的项目,移植到IIS服务器却报错,分析发现是取不到Cookie的值。在网上查了好多资料,大致的原因是存取Cookie时的编码不一致,解决方案主要有以下两种:
一、修改web.config文件
<
globalization fileEncoding
=
"
GB2312
"
requestEncoding
=
"
GB2312
"
responseEncoding
=
"
GB2312
"
/>
二、在存Cookie时进行编码,取的时候再解码
第一种方法貌似不起作用,以下是我用第二种方法的解决方案
1、存入Cookie 用Hashtable存放Cookie的键值对,key为Cookie集的主键,subkey为子键,vlaue为值。
public
void
SetCookie(
string
key, Hashtable ht)
{
HttpCookie cookie = new HttpCookie(key);
cookie.Expires = DateTime.Now.AddMinutes(30);
foreach (DictionaryEntry de in ht)
{
cookie[de.Key.ToString()] = HttpUtility.UrlEncode(de.Value.ToString());
}
HttpContext.Current.Response.AppendCookie(cookie);
}
{
HttpCookie cookie = new HttpCookie(key);
cookie.Expires = DateTime.Now.AddMinutes(30);
foreach (DictionaryEntry de in ht)
{
cookie[de.Key.ToString()] = HttpUtility.UrlEncode(de.Value.ToString());
}
HttpContext.Current.Response.AppendCookie(cookie);
}
2、获取Cookie的值
public
string
GetCookie(
string
key,
string
subkey)
{
string value;
value = HttpContext.Current.Request.Cookies[key][subkey].ToString();
return HttpUtility.UrlDecode(value);
}
{
string value;
value = HttpContext.Current.Request.Cookies[key][subkey].ToString();
return HttpUtility.UrlDecode(value);
}
3、判断Cookie是否存在
public
bool
IsCookieExist(
string
key)
{
if (HttpContext.Current.Request.Cookies[key] != null)
return true;
else
return false;
}
{
if (HttpContext.Current.Request.Cookies[key] != null)
return true;
else
return false;
}
4、初始化Cookie
public
void
InitCookie(
string
key)
{
HttpCookie cookie = new HttpCookie(key);
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.AppendCookie(cookie);
}
{
HttpCookie cookie = new HttpCookie(key);
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.AppendCookie(cookie);
}