1

我正在尝试保存一个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());
    }
4

6 回答 6

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

在此处输入图像描述

于 2013-08-30T17:08:41.993 回答
1

试试这样 -

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

还要检查这个MSDN

于 2013-08-30T16:33:01.057 回答
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);

在 C# 中读取 cookie

于 2013-08-30T16:34:06.193 回答
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(); 
    }
}
于 2013-08-30T16:32:14.693 回答
0

你试过readCookie.Values["userName"]吗?

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

于 2013-08-30T16:34:20.633 回答
0

你可以做

Response.Write("USERNAME: " + readCookie.Value.ToString());
于 2013-08-30T16:31:38.227 回答