0

I have a webpart and I need to set a cookie and read write from/to this cookie.

I tried to read the cookie using Request.Cookies["Cookiename"] and setting the cookie using Response.Cookies["Cookiename"] but it's not working!

0

reading a cookie should be using the correct request method!

read:

string getval = null;
if (Page.Request.Cookies["YourCookieName"] != null)
{
    getval = Page.Request.Cookies["YourCookieName"].Value;
}

its as simple as that ;)

for sharepoint and webparts its Page.Request that we use instead of Request.Cookies as that refers to HttpRequest.Cookies:

http://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies.aspx

when writing you can do:

Response.Cookies

like so:

Create:

HttpCookie c = new HttpCookie("test");
c.Value = "testing";

HttpRequest response = Page.Request;
response.Cookies.Add(c);

write:

string setval = "welcome";
if (Page.Request.Cookies["YourCookieName"] != null)
{
        Page.Request.Cookies["YourCookieName"].Value = setval;
}

create two methods, one for get and one for set, it should have two strings. One for the cookie name and the other for the value (string int to return or set)

    private void setCookie(string val, string cookiename)
    {
        if (Page.Request.Cookies[cookiename] != null)
        {
            Page.Request.Cookies[cookiename].Value = val;
        }
    }

    private string getCookie(string val, string cookiename)
    {
        if (Page.Request.Cookies[cookiename] != null)
        {
             val = Page.Request.Cookies[cookiename].Value ;
        }

        return val;
    }


    private string createCookie(string cookiename,string val)
    {
        HttpCookie c = new HttpCookie(cookiename);
        if (val != null || val != string.empty)
        {
             c.Value = val;

             HttpRequest response = Page.Request;
             response.Cookies.Add(c);   
        }
    }
| improve this answer | |
1

How to create cookie:

HttpCookie createcookie = new HttpCookie("CookieName");
createcookie.Value = "true";
createcookie.Expires = DateTime.Now.AddDays(noDays);
HttpContext.Current.Response.Cookies.Add(createcookie);

Read cookie:

 string mycookieVal;
    HttpCookie readCookie= HttpContext.Current.Request.Cookies["CookieName"];
    if (readCookie!= null)
    {
      mycookieVal = readCookie.Value;
    }

http://social.msdn.microsoft.com/Forums/sharepoint/en-US/c38a0c55-728c-426b-9f56-0f54d66dc80c/create-a-cookie-in-a-sp-web-part

| improve this answer | |
  • I am already doing that, the cookie is there, but it's giving me null value after I load the page again – Jack Nodovan Sep 27 '13 at 11:47
  • Have u tested it in different browsers ? – Pushpendra Sep 27 '13 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.