MVC:cookie不会持久存在

时间:2015-11-19 11:13:46

标签: asp.net-mvc cookies

我在条件中有一个叠加div。如果Cookies["User"]为null,那么我会显示一个覆盖div,它有两个单选按钮和一个提交按钮。

当用户选择radio选项并单击提交按钮时,通过ajax调用时, 我正在调用一个设置cookie的动作。

我已将叠加div放在 _Layout 页面内,因此对于每次调用它都会检查会话。

我的问题是:第一次设置cookie后,它不会第二次持续存在。 下面是我设置cookie的方法:

 public ActionResult SaveUserTypeCookies(string usertype, string returnUrl)
     {
        if (Request.Cookies["User"] != null)
        {
            HttpCookie cookie = Request.Cookies["User"];
            cookie.Values["UserType"] = usertype;
            cookie.Expires = DateTime.MaxValue;
            Response.SetCookie(cookie);
        }
        else
        {
            HttpCookie cookie = new HttpCookie("User");
            cookie.Values["UserType"] = usertype;
            cookie.Expires = DateTime.MaxValue;
            Response.Cookies.Add(cookie);
        }
        return Redirect(returnUrl);
     }

以下是我对叠加div的条件:

 @if ((Request.Cookies["User"]== null))
 {
     <div id="overlay_div" class="overlay"></div>
 }

1 个答案:

答案 0 :(得分:2)

使用此语法获取cookie:

        // 
        // Charsheet_bg
        // 
        this.Charsheet_bg.AutoSize = true;
        this.Charsheet_bg.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("Charsheet_bg.BackgroundImage")));
        this.Charsheet_bg.Controls.Add(this.Charsheet_top);
        this.Charsheet_bg.Dock = System.Windows.Forms.DockStyle.Left;
        this.Charsheet_bg.Location = new System.Drawing.Point(0, 0);
        this.Charsheet_bg.Margin = new System.Windows.Forms.Padding(0);
        this.Charsheet_bg.MinimumSize = new System.Drawing.Size(285, 0);
        this.Charsheet_bg.Name = "Charsheet_bg";
        this.Charsheet_bg.Size = new System.Drawing.Size(285, 488);
        this.Charsheet_bg.TabIndex = 30;
        // 
        // Charsheet_top
        // 
        this.Charsheet_top.BackColor = System.Drawing.Color.Transparent;
        this.Charsheet_top.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("Charsheet_top.BackgroundImage")));
        this.Charsheet_top.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
        this.Charsheet_top.Dock = System.Windows.Forms.DockStyle.Fill;
        this.Charsheet_top.Location = new System.Drawing.Point(0, 0);
        this.Charsheet_top.MinimumSize = new System.Drawing.Size(285, 200);
        this.Charsheet_top.Name = "Charsheet_top";
        this.Charsheet_top.Size = new System.Drawing.Size(285, 488);
        this.Charsheet_top.TabIndex = 31;

并检查cookie是否存在在C#中使用它:

HttpCookie cookie = HttpContext.Request.Cookies.Get("User");

创建并保存cookie:

HttpContext.Request.Cookies["User"] != null