保存和讀取是不一樣的。
COOKIES裡面的特殊字符也要做處理
Dim vType As String
vType = Request("vtype")
Dim ContentStr As String
If vType = "SaveCookies" Then '保存COOKIES
ContentStr = Request("con")
If Response.Cookies("chatbox") Is Nothing Then
Dim cookie As New HttpCookie("chatbox")
Dim dt As DateTime
dt = Now()
Dim ts As New TimeSpan(0, 1, 0)
cookie.Expires = dt.Add(ts)
cookie.Values("con") = ContentStr
Response.Cookies.Add(cookie)
Else
Dim cookie As HttpCookie = Response.Cookies("chatbox")
ContentStr = woody.EncodeBase64(ContentStr)
cookie.Values("con") = ContentStr
End If
Else '讀取 cookies
If Not Request.Cookies("chatbox") Is Nothing Then
Dim cookie As HttpCookie
ContentStr = Request.Cookies("chatbox").Values("con")
ContentStr = woody.DecodeBase64(ContentStr)
Response.Write(ContentStr)
Else
Response.Write("N")
End If
End If
c#版本代碼
public string EncodeBase(string s)
{
string strResult = "";
if (s != "" && s != null)
{
strResult = Convert.ToBase64String(System.Text.ASCIIEncoding.Default.GetBytes(s));
}
return strResult;
}
public string DecodeBase(string s)
{
string strResult = "";
if (s != "" && s != null)
{
strResult = System.Text.ASCIIEncoding.Default.GetString(Convert.FromBase64String(s));
}
return strResult;
}
private void Page_Load(object sender, System.EventArgs e)
{
string vType ;
vType=Request["vtype"];
string ContentStr;
//保存
if(vType=="SaveCookies")
{
ContentStr = Request["con"];
if(Response.Cookies["chatbox"]!=null)
{
HttpCookie cookie =Response.Cookies["chatbox"];
DateTime dt=DateTime.Now ;
TimeSpan ts=new TimeSpan(0,1,0);
cookie.Expires = dt.Add(ts);
cookie.Values["con"] = EncodeBase(ContentStr);
Response.Cookies.Add(cookie);
}
else
{
HttpCookie cookie = Response.Cookies["chatbox"];
ContentStr =EncodeBase(ContentStr);
cookie.Values["con"] = ContentStr;
}
}
else
{
//讀取
if(Request.Cookies["chatbox"] !=null)
{
ContentStr = Request.Cookies["chatbox"].Values["con"];
ContentStr = DecodeBase(ContentStr);
}
else
{
}
}
}