简体   繁体   English

Cookie没有在asp.net mvc中设置

[英]Cookie not setting in asp.net mvc

if (HttpContext.Request.Cookies["time"]==null)
{
    HttpCookie cookie = new HttpCookie("last_visited",DateTime.Now.ToString());
    cookie.Expires = DateTime.Now.AddDays(10);
    HttpContext.Response.Cookies.Add(cookie);
}
else if(HttpContext.Request.Cookies["last_visited"]!=null)
{
    ViewBag.last_visited = HttpContext.Request.Cookies["last_visited"].Value;
}

I am trying to set a cookie in asp.net mvc. 我想在asp.net mvc中设置一个cookie。 Above is my code in the contoller action. 以上是我在控制器操作中的代码。 The purpose of this code is to set a cookie if there is none and read a value if there is a cookie set. 此代码的目的是在没有cookie的情况下设置cookie,如果有cookie集则读取值。

However the after setting the breakpoint i discovered the else if part is never getting executed as if the cookie isn't being set up at all. 然而,在设置断点之后,我发现了else,如果部分永远不会被执行,就好像根本没有设置cookie一样。

What is wrong here ? 这有什么不对?

Is it that the first if statement is checking the wrong cookie? 是第一个if语句检查错误的cookie吗? Should "time" be "last_visited" instead? "time"应该是"last_visited"吗?

Fixed code: 固定代码:

if (HttpContext.Request.Cookies["last_visited"]==null)
{
    HttpCookie cookie = new HttpCookie("last_visited",DateTime.Now.ToString());
    cookie.Expires = DateTime.Now.AddDays(10);
    HttpContext.Response.Cookies.Add(cookie);
}
else if(HttpContext.Request.Cookies["last_visited"]!=null)
{
    ViewBag.last_visited = HttpContext.Request.Cookies["last_visited"].Value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM