BMBM
BMBM

Reputation: 16013

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.

Thanks for any hints!

Upvotes: 7

Views: 8368

Answers (1)

pdr
pdr

Reputation: 6440

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.

Upvotes: 10

Related Questions