Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my cookie not set?

I am playing around again with ASP.NET, and tried to set a cookie in one action which will be read in another action.

The strange thing is: the cookie gets set, but looses its value when accessing another page. Here is my simple controller code:

public class HomeController : Controller
{
    public ActionResult About()
    {
        var cookie = Response.Cookies.Get("sid");
        ViewData["debug"] = "Id: " + cookie.Value;

        return View();
    }

    public ActionResult DoLogin()
    {
        var cookie = new HttpCookie("sid", Guid.NewGuid().ToString());
        cookie.HttpOnly = true;
        Response.Cookies.Add(cookie);

        return RedirectToAction("About");
    }
}

The flow is like this: first I access /Home/DoLogin, then I get redirected to /Home/About which should actually output the value of the sid cookie. But the cookie does not have any value.

  • Cookies are not disabled in my browser
  • I know that ASP.NET has its own session handling mechanism, just playing around and stumbled upon this cookie problem

Thanks for any hints!

like image 454
Max Avatar asked Dec 18 '10 14:12

Max


1 Answers

In your About action, use Request.Cookies instead.

As a short explanation: When you set something in Response.Cookies, that cookie is sent to the client which stores it. On each subsequent Request to the same namespace, until the expiry date is reached, the client sends that cookie to the server, which stores it in Request.Cookies.

like image 96
pdr Avatar answered Oct 07 '22 22:10

pdr