Ruby
Ruby

Reputation: 969

How to read a cookie

I'm trying to save a cookie and then read it. Unable to compile as there is an error in code for the lines (readcookie[....] )-

Response.Write("USERNAME: " + readCookie["userInfo"]["userName"].ToString());

which says - "best overloaded method match for string.this[int] has invalid arguments.

If I write,

 Response.Write("USERNAME: " + readCookie["userInfo"][0].ToString());

then I can compile. It gives the 'data saved' message on save_click but on read_click, it shows an error - object reference invalid. Is it correctly saving a cookie in the first place. How can I read from it. Here's my code:

protected void btnSaveCookie_Click(object sender, EventArgs e)
    {
        HttpCookie myCookie = new HttpCookie("userInfo");
        myCookie.Values["userName"] = "Patrick";
        myCookie.Values["lastVisit"] = DateTime.Now.ToString();
        Response.Cookies.Add(myCookie);
        Response.Write("Data Stored Into Cookie....");
    }

protected void btnReadCookie_Click(object sender, EventArgs e)
    {
        HttpCookie readCookie = Request.Cookies.Get("userInfo");
        Response.Write("USERNAME: " + readCookie["userInfo"]["userName"].ToString());
        Response.Write("LAST VISIT: " + readCookie["userInfo"]["lastVisit"].ToString());
    }

Upvotes: 1

Views: 2208

Answers (6)

Win
Win

Reputation: 62300

Here is the helper methods to read and write cookies.

/// <summary>
/// Sets cookie.
/// </summary>
/// <param name="cookieName">Cookie name</param>
/// <param name="cookieValue">Cookie value</param>
/// <param name="days">Days to be expired</param>
public static void SetCookie(string cookieName, string cookieValue, int days)
{
    try
    {
        var dt = DateTime.Now;

        var cookie = new HttpCookie(cookieName);
        cookie.Value = cookieValue;
        cookie.Expires = dt.AddDays(days);

        HttpContext.Current.Response.Cookies.Add(cookie);
    }
    catch (Exception ex)
    {
        // Log error
    }
}

/// <summary>
/// Gets cookie string
/// </summary>
/// <param name="cookieName">Cookie name</param>
/// <returns>Cookie string</returns>
public static String GetCookie(String cookieName)
{
    try
    {
        if (HttpContext.Current.Request.Cookies[cookieName] == null)
            return String.Empty;

        return HttpContext.Current.Request.Cookies[cookieName].Value;
    }
    catch (Exception ex)
    {
        // Log error
        return String.Empty;
    }
}

Usage

protected void btnSaveCookie_Click(object sender, EventArgs e)
{
    SetCookie("userName", "Patrick", 1); // Save for one day
    SetCookie("lastVisit", DateTime.Now.ToString(), 1);
}

protected void btnReadCookie_Click(object sender, EventArgs e)
{
    Response.Write("USERNAME: " + GetCookie("userName"));
    Response.Write("LAST VISIT: " + GetCookie("lastVisit"));
}

Answer to original question

If you use Multi-Valued Cookies (Subkeys), you want to retrieve the value as readCookie["xxx"].

protected void btnSaveCookie_Click(object sender, EventArgs e)
{
    HttpCookie myCookie = new HttpCookie("userInfo");
    myCookie.Values["userName"] = "Patrick";
    myCookie.Values["lastVisit"] = DateTime.Now.ToString();
    Response.Cookies.Add(myCookie);
    Response.Write("Data Stored Into Cookie....");
}

protected void btnReadCookie_Click(object sender, EventArgs e)
{
    HttpCookie readCookie = Request.Cookies.Get("userInfo");

    Response.Write("USERNAME: " + readCookie["userName"]);
    Response.Write("LAST VISIT: " + readCookie["lastVisit"]);
}

enter image description here

Upvotes: 2

Garrison Neely
Garrison Neely

Reputation: 3289

Have you tried readCookie.Values["userName"]?

For more info: http://msdn.microsoft.com/en-us/library/system.web.httpcookie.values.aspx

Upvotes: 0

user240141
user240141

Reputation:

Read cookie:

HttpCookie aCookie = Request.Cookies["UserSettings"];
if(aCookie != null) {
     object userSettings = aCookie.Value;
} else {
     //Cookie not set.
}

To set a cookie:

HttpCookie cookie = new HttpCookie("UserSettings");

cookie["UserSettings"] = myUserSettingsObject;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);

Reading cookie in c#

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172618

Try like this:-

HttpCookie aCookie = Request.Cookies["UserSettings"];
string lang = Server.HtmlEncode(aCookie.Value);

Also check this MSDN

Upvotes: 1

Satpal
Satpal

Reputation: 133453

Try this

if (Request.Cookies["userInfo"] != null)
{
    string userSettings, lastVisit ;
    if (Request.Cookies["userInfo"]["userName"] != null)
    {
        userSettings = Request.Cookies["userInfo"]["userName"].ToString(); 
    }
    if (Request.Cookies["userInfo"]["lastVisit"] != null)
    {
        lastVisit = Request.Cookies["userInfo"]["lastVisit"].ToString(); 
    }
}

Upvotes: 1

Ehsan
Ehsan

Reputation: 32719

you can do

Response.Write("USERNAME: " + readCookie.Value.ToString());

Upvotes: 0

Related Questions