Win Coder
Win Coder

Reputation: 6756

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

Upvotes: 0

Views: 2783

Answers (1)

Rob
Rob

Reputation: 5588

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;
}

Upvotes: 2

Related Questions