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 ?

1
  • 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. Commented Mar 25, 2013 at 17:40

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

ya my bad.Haven't slept for 2 days, my head is rolling like a ball. Anyways thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.