【问题标题】:ASP.NET set default value for cookiesASP.NET 为 cookie 设置默认值
【发布时间】:2015-03-18 20:53:42
【问题描述】:

所以我做了两页,一页用于设置,另一页用于标签和图像。我想要的是当没有 cookie 时 img_gm.BorderWidth 和 img_gm.Bordercolor 默认为 1 和 Black,但似乎错误总是发生在 libe "img_gm.BorderWidth = Convert.ToInt32(cookie["width"] );"任何帮助将不胜感激。

*我在设置页面中放置文本框、下拉列表和单选按钮以获取cookies["width"]、cookies["color"]和cookies["font"]的输入

protected void Page_Load(object sender, EventArgs e) {

    HttpCookie cookie = Request.Cookies["settings"];
    if (Request.Cookies.AllKeys.Contains("settings") == null)
    {
        cookie["width"] = "1";
        cookie["color"] = "Black";
        cookie.Expires = DateTime.Now.AddDays(14);
        Response.Cookies.Add(cookie);
    }
    else
    {

        img_gm.BorderWidth = Convert.ToInt32(cookie["width"]);
        img_gm.BorderColor = System.Drawing.Color.FromName(cookie["color"]);
        switch (cookie["font"])
        {
            case "Bold":
                lbl_desc.Font.Bold = true;
                break;
            case "Italic":
                lbl_desc.Font.Italic = true;
                break;
            case "Overline":
                lbl_desc.Font.Overline = true;
                break;
            case "Underline":
                lbl_desc.Font.Underline = true;
                break;
        }

    }

【问题讨论】:

  • 为什么要在 if 块中检查 Response.Cookes.AllKeys?也许应该是Request
  • 哦,是的,我混淆了这些,我在我的代码中写了请求,但它仍然给我一个错误“img_gm.BorderWidth = Convert.ToInt32(cookie["width"]);”跨度>
  • 如果你设置断点并检查cookie["width"]值它有什么值?也许它有一些不是整数的旧测试值,所以它在解析过程中失败了?和cookie只需要在browserR中清除?

标签: c# asp.net cookies


【解决方案1】:

一个巧妙的技巧是将它们更改为类中的属性:

public int CookieWidth {
  get {
    int width;
    var str = String.Format("{0}", cookie["width"]);
    if (!Integer.TryParse(str, width)) {
      width = 1;
    }
    return width;
  }
  set {
    cookie["width"] = value;
  }
}

您也可以使用 Color 来做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-14
    • 2016-11-16
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2011-09-04
    相关资源
    最近更新 更多