【问题标题】:c# cookies not being written toc# cookie 没有被写入
【发布时间】:2011-04-16 04:06:52
【问题描述】:

在我的内容页面上,我有代码(在 page_load 中):

    if (Master.pageAction == "remove")
    {
        int removeProductID = int.Parse(Request.QueryString["ID"]);
        int removeOptionID = int.Parse(Request.QueryString["optID"]);
        Master.myBasket.removeFromBasket(removeProductID, removeOptionID);
        //Response.Redirect("viewBasket.aspx");
    }

从篮子中移除函数定义为:

// Removes item from a basket
public void removeFromBasket(int itemsID, int optionsID)
{
    Page myPage = (Page)HttpContext.Current.Handler;

    this.setCookieString("");
    myPage.Response.Write("done");
}

它会调用:

// Sets cookie date
public void setCookieString(string cookiesData)
{
    Page myPage = (Page)HttpContext.Current.Handler;
    HttpCookie basketCookie = new HttpCookie("basket");
    basketCookie["items"] = cookiesData;
    basketCookie.Expires = DateTime.Now.AddDays(7d);
    myPage.Response.Cookies.Add(basketCookie);
}

我在其他页面上使用了 setcookiestring 函数,它工作正常,但是这个函数(从购物篮中删除)没有设置 cookie!它正在将“完成”写入页面顶部,因此函数正在执行。

没有警告,没有错误,只是没有更新 cookie。

【问题讨论】:

  • 出于好奇,你为什么要在 HTTP 响应中添加一个值为 "" 的 cookie?
  • 这只是为了测试,我会将真实数据放入其中,但我只是看看它是否将其设置为任何东西。无论我传入什么,cookie 的值都不会改变。
  • 另外,如果在(主)页面之外,只需使用HttpContext.Current.Response,更容易以母版页的Response 属性访问响应(就像在Page 中一样)。
  • 是的,我也想这么说——我以为你在处理 HttpHandler 时只使用 HttpContext.Current.Handler——但后来我看到对 Page 的演员表有点困惑。
  • 为什么不通过设置过期来删除cookie呢?另一个问题是为什么不使用 Value 属性——你是在创建多值 cookie。最后一件事,您能否从 Fiddler 或 Firebug 中查看哪些 cookie 数据正在发送到浏览器。

标签: c# asp.net cookies setcookie


【解决方案1】:

问题来自最初由 Javascript 设置的 cookie,没有设置 path= 属性。 Javascript 默认 cookie 路径为当前文件夹,而 ASP.net 默认为 /

在 Javascript 设置 cookie 方法中设置 path=/ 解决了这个问题。

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2019-11-19
    • 2019-09-21
    相关资源
    最近更新 更多