Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 Doesn't save cookie in browser

I've been trying to save a plain text in a cookie in my browser with MVC4, but for some reason it never saves in the browser. I tested in IE, Chrome and FireFox.

I've been trying different solutions on StackOverflow, but none of them have worked for me yet. I have no clue what I'm doing wrong and I hope someone is able to assist me with this problem.

The code I've been using:

if (Request.Cookies.AllKeys.Contains("testKanti"))
{
    // Never makes it here.
}
else
{
    HttpCookie cookie = new HttpCookie("testKanti");
    cookie.Value = "testKanti";
    cookie.Expires = DateTime.UtcNow.AddYears(1);

    Response.Cookies.Remove("testKanti");
    Response.SetCookie(cookie);
}

I've also tried Response.Cookies.Add(), but that didn't work either. Is anyone familiar with this problem?

like image 473
Mittchel Avatar asked Mar 18 '26 01:03

Mittchel


1 Answers

Have you tried to use both strings?

Request.Cookies.Add(cookie);
Response.SetCookie(cookie);

I've tried and in my case it works

if (Request.Cookies.AllKeys.Contains("testKanti"))
{
    // We are here
}
like image 138
Andrew Avatar answered Mar 19 '26 14:03

Andrew