对cookie使用的教训

昨天使用了cookie存用户IP分区信息,之前也一直使用没问题。

但是上线后一直很诡异,不是网站多域名问题,后面发现是存储数据有中文,哎,这个又忘了编码。

 
  HttpCookie authCookie = Request.Cookies["ipAddress"];
                if (authCookie == null)
                {
                    XXXDAL.Instance.GetCountryByIP(Util.GetIP(), out partition, out city);
                    HttpCookie aCookie = new HttpCookie("ipAddress");
                    aCookie.Values["partition"] = partition.ToString();
                    aCookie.Values["city"] = HttpUtility.UrlEncode(city);
                    aCookie.Expires = DateTime.Now.AddDays(7);
                    Response.Cookies.Add(aCookie);
                }
                else
                { 
                    if(Request.Cookies["ipAddress"]["partition"]!=null&& int.TryParse(Request.Cookies["ipAddress"]["partition"].ToString(),out partition))
                    {
                        partition=int.Parse(Request.Cookies["ipAddress"]["partition"]);
                    }
                    if (Request.Cookies["ipAddress"]["city"] != null)
                    {
                        city = HttpUtility.UrlDecode(Request.Cookies["ipAddress"]["city"]);
                    }

 

限制cookie的域范围

Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = "support.contoso.com";

 确定浏览器是否接受 Cookie

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if (Request.QueryString["AcceptsCookies"] == null)
        {
            Response.Cookies["TestCookie"].Value = "ok";
            Response.Cookies["TestCookie"].Expires =
                DateTime.Now.AddMinutes(1);
            Response.Redirect("TestForCookies.aspx?redirect=" +
                Server.UrlEncode(Request.Url.ToString()));
        }
        else
        {
            Label1.Text = "Accept cookies = " +
                Server.UrlEncode(
                Request.QueryString["AcceptsCookies"]);
        }
    }
}

参考:http://msdn.microsoft.com/zh-cn/library/ms178194(v=VS.80).aspx

posted @ 2013-01-07 10:47  VORO  阅读(197)  评论(0编辑  收藏  举报