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!
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);
}
}
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;
}