0
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. 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.

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.

What is wrong here ?

Win Coder
  • 6,628
  • 11
  • 54
  • 81
  • try fiddler to examine the response. Copying your code into an MVC4 controller I see {code} Set-Cookie: last_visited=25/03/2013 10:38:51; expires=Thu, 04-Apr-2013 17:38:52 GMT; path=/ {code} in Fiddler. – Dylan Mar 25 '13 at 17:40

1 Answers1

2

Is it that the first if statement is checking the wrong cookie? Should "time" be "last_visited" instead?

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;
}
Rob
  • 5,578
  • 3
  • 23
  • 28