简体   繁体   中英

How to use a cookie as a property with ASP.Net (c#)

I am trying to use a property in the back end of a page to set a cookie, I am getting strange results, not sure if what I am doing is the correct way to use cookies.

Anyway my code is below, if you have any ideas on how best to handle this or an example where it has been done already I would be grateful for a response Thanks.

    int CurrentID
    {
        get
        {
            if (Request.Cookies["CurrentID"] == null)
                Response.Cookies.Add(new HttpCookie("CurrentID", "0"));
            return Request.Cookies["CurrentID"].Value.AsID();
        }
        set
        {
            if (Request.Cookies["CurrentID"] != null)
                Response.Cookies.Remove("CurrentID");
            Response.Cookies.Add(new HttpCookie("CurrentID", value.ToString()));
        }
    }

In the getter, you're returning the cookie in the request, but you're not setting it in the request in the case where it doesn't exist.

Perhaps try:

if (Request.Cookies["CurrentID"] == null)
{
    Response.Cookies.Add(new HttpCookie("CurrentID", "0"));
    return 0;
}
return Request.Cookies["CurrentID"].Value.AsID();

Figured out when removing then adding a cookie to Responce it does not remove from Reequest and so adds a new cookie with the same name, so when getting the property it got the first version of the cookie which was an old value.

Anyway the solution is as follows.

    int CurrentID
    {
        get
        {
            if (Request.Cookies["CurrentID"] != null)
            {
                return Request.Cookies["CurrentID"].Value.AsID();
            }
            else
            {
                Response.Cookies.Add(new HttpCookie("CurrentID", "0"));
                return 0;
            }
        }
        set
        {
            if (Response.Cookies["CurrentID"] != null)
            {
                Response.Cookies.Remove("CurrentID");
                Request.Cookies.Remove("CurrentID");
            }
            Response.Cookies.Add(new HttpCookie("CurrentID", value.ToString()));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM