如何阅读cookie

时间:2013-08-30 16:29:04

标签: c# asp.net

我正在尝试保存cookie然后阅读它。无法编译,因为行代码中存在错误(readcookie [....]) -

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

其中 - “string.this [int]的最佳重载方法匹配具有无效参数。

如果我写,

 Response.Write("USERNAME: " + readCookie["userInfo"][0].ToString());
然后我就可以编译了。它在save_click上提供'数据已保存'消息,但在read_click上,它显示错误 - 对象引用无效。它是否正确地保存了cookie。我该怎么读呢。这是我的代码:

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

6 个答案:

答案 0 :(得分:2)

以下是读取和写入cookie的帮助方法。

/// <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;
    }
}

用法

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

回答原始问题

如果您使用多值Cookie(子键),则需要将值检索为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

答案 1 :(得分:1)

试试这个

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

答案 2 :(得分:1)

尝试this: -

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

同时检查此MSDN

答案 3 :(得分:1)

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#

答案 4 :(得分:0)

你可以做到

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

答案 5 :(得分:0)

您是否尝试过readCookie.Values["userName"]

了解更多信息:http://msdn.microsoft.com/en-us/library/system.web.httpcookie.values.aspx