2017-08-12 273 views
1

我無法將cookie值存儲在cookie中。這裏是我的代碼:無法在cookie中存儲cookie值

namespace CookieCreation.Controllers 
{ 
    public class CookieController : Controller 
    { 
     // GET: /<controller>/ 
     public IActionResult Index() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public IActionResult WriteCookie(String CookieName, String CookieValue, bool IsPersistent) 
     { 
      if (IsPersistent) 
      { 
       CookieOptions cookies = new CookieOptions(); 
       cookies.Expires = DateTime.Now.AddDays(1); 
       Response.Cookies.Append(CookieName, CookieValue, cookies); 
      } 
      else 
      { 
       Response.Cookies.Append(CookieName, CookieValue); 
      } 
      ViewBag.Message = ("Sucessful"); 
      return View("Index"); 
     }  

     public IActionResult ReadCookie() 
     { 
      ViewBag.CookieValue = Request.Cookies["CookieName"]; 
      return View(); 
     } 
    } 
} 

回答

0

你如何確定cookie不存儲?使用Chrome開發人員工具,應用程序/ Cookie查看是否創建了Cookie。

我用你的代碼與下面的Index.cshtml和一切工作,cookie被存儲和使用您的代碼閱讀:

<h1>Index</h1> 
<p>Last operation: @ViewBag.Message</p> 

@{ 
    using(Html.BeginForm("WriteCookie", "Cookie", new { CookieName = "CookieName", IsPersistent = false}, FormMethod.Post )) { 
     <input type="text" value="42" name="CookieValue" /> 
     <input type="submit" value="post"/> 
    } 
}